Md Faisal
Md Faisal

Reputation: 2991

Creating an array of ArrayList which store object of Generic type

I have to create an array of ArrayList which is storing an object of the generic type.

ArrayList<Entry>[] bucket;

when I initialize this to

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

I get java.lang.ClassCastException at runtime.

Entry class uses generics. Below is the code:

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

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

After going through several posts on why Array of Objects cannot be cast to an ArrayList of a generic type, I have understood my problem. But I am not able to get my head around this to solve my particular case.

Some of the solutions involved:

Changing it FROM "an array of ArrayList" TO "an ArrayList of ArrayList",
but I can not do that in my case.

Full code:

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);
    }
}

Upvotes: 2

Views: 1486

Answers (2)

Gurwinder Singh
Gurwinder Singh

Reputation: 39467

You can't create arrays of generic type. Use this instead:

ArrayList<Entry>[] bucket = new ArrayList[m];

It shows unchecked warning though, which you can suppress using @SuppressWarnings("unchecked") like so:

@SuppressWarnings("unchecked")
ArrayList<Entry>[] bucket = new ArrayList[m];

Upvotes: 2

Kiran Kumar
Kiran Kumar

Reputation: 1051

Object can be cast to ArrayList only if the actual object it holds is an arrayList. i.e let's look at the below code,

Object obj = new ArrayList<String>();   // object variable holding array list type.
ArrayList<String> arr = (ArrayList<String>) obj;

Upvotes: 0

Related Questions