0

Quick question. Let's say I define an ArrayList bigArrayList as a ArrayList of ArrayList . Can my bigArrayList contain other data types other than a ArrayList? Other data types like int, String, objects or a simple array?

Example code of ArrayList creation:

    ArrayList<ArrayList<String>> bigArrayList = new ArrayList<ArrayList<String>>();
    ArrayList<String> smallArrayList = new ArrayList<String>();
    bigArrayList.add(smallArrayList);

    int myInt = 12;
    bigArrayList.add(smallArrayList); //Acceptable??

Also how would I go about modifying smallArrayList once it's added to bigArrayList? Thanks in advance.

2
  • You tell me...What's the whole point of generics..? Commented Mar 26, 2014 at 10:29
  • try to store different data and tell us what happened.. Commented Mar 26, 2014 at 10:29

2 Answers 2

3

No, ArrayList of ArrayLists cannot contain other elements except ArrayList. You will get a compiler error if you try putting something else in.

You can, however, define the bigArrayList as ArrayList bigArrayList= new ArrayList(); without any type information and you can store whatever you want in. This is very dangerous practice hence the generics.

Sign up to request clarification or add additional context in comments.

Comments

2

The point of using Generics (the "< >" thing) in collections is to tell the compiler that you are only putting a particular type (and its subclass) of objects into it. Therefore you cannot put other types into bigArrayList. You could work around this by not using Generics, as darijan suggested. As he also warned, this is not recommended.

For modifying smallArrayList after its added into bigArrayList, either the code required to modify recovers the smallArrayList's reference from bigArrayList (e.g. bigArrayList.get(0) and modify) or you retain the smallArrayList reference and pass it onto the modify code.

BTW, what are you trying to achieve with the code? What you're trying to do here is rather unusual, to say the least.

1 Comment

It is better practice to use a generalized generic vs. leaving out all generics. If you really can't tell in advance what you want to put in your collection, you should use ArrayList<Object> in preference to ArrayList.

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.