2

Can anybody tell me how to create an array-arraylist the right way ?!

.\File.java:5: warning: [unchecked] unchecked conversion
        ArrayList<myObjectType> myParkingLotArray[] = new ArrayList[3];
                                                 ^
  required: ArrayList<Vehicle>[]
  found:    ArrayList[]
1 warning

I want an arry (or any other solution) which stores 3 arraylists. How to add objects to the arrylists would be nice to know too.

ParentArray

  1. ChildArrayList1
  2. ChildArrayList2
  3. ChildArrayList3

Im happy for any Help

SOLUTION:

public class myClass {
  ArrayList<myObjectType>[] myArryName= new ArrayList[3];

  public void addLists() {
    myArryName[0] =  new ArrayList<myObjectType>();
    myArryName[1] =  new ArrayList<myObjectType>();
    myArryName[2] =  new ArrayList<myObjectType>();
  }
}

The warning can be ignored or suppressed.

3 Answers3

8

You can not create an Array of classes that use generic types - see here!

And there is no way to work around that error message. The compiler tells you: this ain't possible!

Instead - simply stay with one concept. There is no point of mixing arrays and Lists anyway. Just go for

List<List<Vehicle>> parents = new ArrayList<>();

And then

List<Vehicle> someChild = new ArrayList<>();

To finally do something like

parents.add(someChild);
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You can do this with a cast

ArrayList<myObjectType>[] myParkingLotArray = (ArrayList<myObjectType>[]) new ArrayList[3];

However, I agree with GhostCat you should try to use arrays or lists but not mix them. a List<List<myObjectype>> would be better.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You cannot create arrays of parameterized types.

What you can do insteade is the following:

List [] arrayOfLists = new ArrayList[10];
arrayOfLists[0] = new ArrayList<Vehicle>();

but you can't be sure that all the lists will be List of the same type.

Otherwise you can use simply List of Lists in this way:

List<List<Vehicle>> listOfLists = new ArrayList<>();
List<Vehicle> list = new ArrayList<>();
listOfLists.add(list);
granmirupa
  • 2,780
  • 16
  • 27