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.

0

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

ArrayList[] myParkingLotArray = new ArrayList[3]; this worked ?!
@2vkIYKaT4mNOMe0uRjtsoT5AF you can suppress the warning with @SuppressWarning("checked")
@2vkIYKaT4mNOMe0uRjtsoT5AF true, though you don't have a generic type anymore.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.