package org.itscool.commons.collection;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 重複キーを保持するLinkedListのラッパークラス
 * @author kanou
 *
 */
public class KeyLinkedList{
    LinkedList list = new LinkedList();
    
    public Object put(Object key, Object obj){
        list.addLast(new ElementRapper(key, obj));
        return obj;
    }
    
    public Object get(int index){
        if(list.size()<=index){
            return null;
        }else{
            ElementRapper rapper = (ElementRapper)list.get(index);
            return rapper.getObj();
        }
    }
    
    public Object getKey(int index){
        if(list.size()<=index){
            return null;
        }else{
            ElementRapper rapper = (ElementRapper)list.get(index);
            return rapper.getKey();
        }
    }
    
    public Object get(Object key){
        int size = list.size();
        for(int i=0; i<size; i++){
            ElementRapper rapper = (ElementRapper)list.get(i);
            if(rapper.getKey().equals(key)){
                return rapper.getObj();
            }
        }
        return null;
    }
    
    public List getList(Object key){
        LinkedList result = new LinkedList();
        int size = list.size();
        for(int i=0; i<size; i++){
            ElementRapper rapper = (ElementRapper)list.get(i);
            if(rapper.getKey().equals(key)){
                result.add(rapper.getObj());
            }
        }
        return result;
    }
    
    public int size(){
        return list.size();
    }
    
    public Object remove(Object key){
        int size = list.size();
        for(int i=0; i<size; i++){
            ElementRapper rapper = (ElementRapper)list.get(i);
            if(rapper.getKey().equals(key)){
                return list.remove(i);
            }
        }
        return null;
    }
    
    public void clear(){
        list.clear();
    }
    
    public Set keySet(){
        Set set = new HashSet();
        int size = list.size();
        for(int i=0;i<size;i++){
            ElementRapper rapper = (ElementRapper)list.get(i);
            set.add(rapper.getKey());
        }
        return set;
    }
    
    public Collection values(){
        LinkedList values = new LinkedList();
        int size = list.size();
        for(int i=0;i<size;i++){
            ElementRapper rapper = (ElementRapper)list.get(i);
            values.add(rapper.getObj());
        }
        return values;
    }
}

