简体   繁体   中英

Creating an ArrayList of generic ArrayLists in Java

I'm trying to bucket sort an ArrayList of objects. The objects are generic (not sure if I'm using the correct terminology here) in that they are composed of an int (the key) and a generic object (E). Looks like this:

public pair(int key, E value){
    this.key = key;
    this.value = value;
}

In my sort method, I try to create an ArrayList of ArrayLists and then sort by the key of the objects. I can't figure out how to add a new ArrayList to an ArrayList though. Here's my code, and I've commented the line on which I know I go awry.

public ArrayList<V> bucketSort(ArrayList<V> entries) {
    List<ArrayList<V>> bucket = new ArrayList<>();
    for(int i = 0; i < entries.size(); i++){
        int key = entries.get(i).getKey();

        if (bucket.get(key) == null){
            bucket.add(key, new ArrayList<V>()); //This is where things go bad
        }

        bucket.get(key).add(entries.get(i));
    }

    int k = 0;

    for(int i = 0; i < bucket.size(); i++){
        if(bucket.get(i) != null) {
            for (int j = 0; j < bucket.get(i).size(); j++){
                entries.set(k++, bucket.get(i).get(j));
            }
        }
    }


    return entries;
}

I'm getting very confused with all the various casting and stuff. Generics is frustrating. I'm fairly certain that I'm creating the bucket list incorrectly, or I'm trying to add the ArrayList in the wrong way. Any input would be appreciated.

List<ArrayList<V>> bucket = new ArrayList<>();

bucket is list of arraylist . But you are trying to add key, value pair here

  bucket.add(key, new ArrayList<V>());

I believe you need bucket as map where key can be any object and value as list

I suggest that you use a map (hashmap) instead.

Map<Integer,ArrayList<>> test = new HashMap<>();

Where the Integer is your key and the Arraylist is your value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM