有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建存储泛型类型对象的ArrayList数组

我必须创建一个ArrayList数组来存储泛型类型的对象

ArrayList<Entry>[] bucket;

当我把它初始化为

bucket=(ArrayList<Entry>[])new Object[m];

我喜欢java。lang.ClassCastException在运行时

Entry类使用泛型。代码如下:

class Entry<K,V>{
    K key;
    V value;

    public Entry(K key,V value){
        this.key=key;
        this.value=value;
    }

在阅读了几篇关于为什么不能将对象数组转换为泛型类型的ArrayList的文章之后,我理解了我的问题。但我无法通过思考来解决我的特殊情况

其中一些解决方案包括:

将其从“ArrayList的数组”更改为“ArrayList的数组列表”
但就我而言,我不能这样做

完整代码:

import java.util.ArrayList;
class MyHashMap<K,V>  {

    int m;
    int loadFactor;
    int n;

    ArrayList<Entry>[] bucket;

    public MyHashMap(){
        this(10,2);
    }
    public MyHashMap(int m){
        this(m,2);
    }
    public MyHashMap(int m,int loadFactor){
        this.m=m;
        this.loadFactor=loadFactor;
        n=0;

        bucket=(ArrayList<Entry>[])new Object[m];

    }

    class Entry{
        K key;
        V value;

        public Entry(K key,V value){
            this.key=key;
            this.value=value;
        }

        public int hashCode(){
            return 0;
        }
    }


    public void put(K key, V value){    
        Entry entry=new Entry(key,value);
        int hash=entry.hashCode();
        int index=hash%m;
        bucket[index].add(entry);
    }

    public static void main(String[] args) {
        MyHashMap hashMap=new MyHashMap();

        hashMap.put("faisal",2);
    }
}

共 (0) 个答案