初始化通用构造函数

时间:2015-04-30 17:26:08

标签: java

当我执行以下操作时:

 IMiniMap<String,Integer> map = new SimpleListMM<String,Integer>();
 IMiniMap<Double,ArrayList<Object>> map2 = new SimpleListMM<Double,ArrayList<Object>>();
 IMiniMap<String,Integer> map = new SimpleListMM<String,Integer>();

然后我收到错误说The constructor SimpleListMM<...,...>() is undefined。我不允许使用setter方法,而我在构造函数中所做的就是分配ArrayList<K> smthArrayList<V>。什么是在类中初始化泛型构造函数的方法?我该如何解决这个问题?

import java.util.*;

public class FastGetListMM<K,V> extends AbstractListMM<K,V> implements Comparator<K> {

    // Comparator used to sort elements; may be null if elements are Comparable
    public final Comparator<K> cmp = new Comparator<K>();    
    //private List<K> keys;;
    //private List<V> values;

    // Assume elements must be comparable
    public FastGetListMM(ArrayList<K> keys, ArrayList<V> values)
    {
        super(keys, vals);
        this.cmp = new Comparator<K>();
    }

    // Use the given comparator to sort the keys
    public FastGetListMM(Comparator<K> cmp)
    {
        super(cmp);
        //this.cmp = cmp;
    }

    @Override
    public int indexOf(K key) {

        return 0;
    }

    @Override
    public V put(K key, V value) {

        return null;
    }

    @Override
    public int compare(K arg0, K arg1) {
        // TODO Auto-generated method stub
        return 0;
    }

}

SimpleListMM类:

import java.util.*;

public class SimpleListMM<K,V> extends AbstractListMM<K,V> {

    //protected ArrayList<K> keys;
    //protected ArrayList<V> vals;

    // No special parameters required
    public SimpleListMM(ArrayList<K> keys, ArrayList<V> vals)
    {
        super(keys, vals);
    }

    // Scan through the list of keys linearly searching for the given
    // key. If not present, return a negative number.
    public int indexOf(K key)
    {
        K index = null;
        for(int i = 0; i < keys.size(); i++)
        {
            if(keys.get(i) != key)
                return -1;
            else 
                index = keys.get(i);
        }
        return (Integer) index;
    }

    // Locate the given key and replace its binding with the given
    // value. If not present, add the key and value onto the end of
    // their respective lists.
    public V put(K key, V value)
    {
        for(int i = 0; i < keys.size(); i++)
        {
            if(keys.get(i) == key)
                vals.set((Integer)keys.get(i), value);
            else
            {
                keys.add(key);
                vals.add(value);
            }
        }
        return (V)vals;
    }
}

1 个答案:

答案 0 :(得分:1)

您的类没有no-arg构造函数,因此编译错误。在两个类中添加适当的构造函数:

public class SimpleListMM<K,V> extends AbstractListMM<K,V> {

    public SimpleListMM() {
        //some initialization logic
        //maybe like this
        super(new ArrayList<K>(), new ArrayList<V>());
    }

    public SimpleListMM(ArrayList<K> keys, ArrayList<V> vals) {
        super(keys, vals);
    }
}