user1203861
user1203861

Reputation: 1217

Declare an Array of ArrayLists of certain object

i need to make an array of arraylists of an object.

i have tried two ways , but i can't access object's properties from the array elements.

i've tried :

     ArrayList<Word>[] SubList = (ArrayList<Word>[])new ArrayList(MainList.size()); 

AND :

    ArrayList<Word>[] SubList= new ArrayList[MainList.size()];

AND:

           ArrayList<Word>[] SubList= (ArrayList<Word> [])new ArrayList[MainList.size()];

What i would like to do is to call a method from the object inside the array

like this :

    SubList[0].get(0).method();

Thanks In Advance

Upvotes: 2

Views: 1380

Answers (3)

Milosz
Milosz

Reputation: 3074

Java doesn't support Arrays of generics very well. However, if you insist on having the top-level structure being an Array type object, you could work around this limitation by creating a new class that extends the generic:

import java.util.ArrayList;

class Test {
    private static class StringArrayList extends ArrayList<String> {}

    public static void main(String[] args) {
        StringArrayList[] sublist = new StringArrayList[1];
        int stringLength;

        sublist[0] = new StringArrayList();
        sublist[0].add("Hello");

        stringLength = sublist[0].get(0).length();
        System.out.println(stringLength);
    }
}

It's not pretty, but it works. It's fine for a personal project but might be a bit too cluttered and C++-like for a large Java enterprise ;)

Upvotes: 0

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49187

To avoid working with low level Arrays and to preserve type safety, you could make a list of a list

List<List<Word>> listOfList = 
         new ArrayList<List<Word>>(new ArrayList<List<Word>>());

Which you then could access like

Word word = listOfList.get(0).get(0);

Upvotes: 4

rlegendi
rlegendi

Reputation: 10606

Generally you cannot do that, because it is not type safe.

See Angelika Langer's Gererics FAQ about the issue (and some additional notes here).

What you can do however, is writing code without using generics and type-casting each time. You'll get a lot of warnings but note that you are sailing on dangerous waters indeed.

Upvotes: 1

Related Questions