Gopal Samant
Gopal Samant

Reputation: 2269

How to use a list of a list of Objects in java?

In the below mentioned program array is a List passed as an argument to this function. The task is to cut the array into lists of LookupTable of defined size and then add them into binlists. In this case what should be the declaration of binlists? Should it be List ? Because either way it gives me an error at the add() function. It works totally fine if I use all the Lists mentioned as raw type. But my intention is to make it parametric.

    protected List<LookupTable> binlists;
    binlists = new ArrayList<LookupTable>(nofbins);

    while(chunk+binsize <= tot_size)
    {
        List tempsort = (List<LookupTable>)arry.subList(chunk,chunk+binsize);
        System.out.println(tempsort.size());
        binlists.add(tempsort);
        chunk = chunk+binsize;
    }

Upvotes: 0

Views: 100

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213223

You need to use addAll method to add a list to an existing list: -

binlists.addAll(tempsort);

And you should always declare your List to be of generic type.

So, declare your tempSort list as a generic list of type LookUpTable: -

List<LookupTable> tempsort = 
                  (List<LookupTable>)arry.subList(chunk,chunk+binsize);

In fact, you can save yourself from that typecast if you declare your arry list too as generic type.

Upvotes: 1

Related Questions