1

I have a scenario where I have to work with multiple lists of data in a java app... Now each list can have any number of elements in it... Also, the number of such lists is also not known initially...

Which approach will suit my scenario best? I can think of arraylist of list, or list of list or list of arraylist etc(ie combinations of arraylist + list/ arraylist+arraylist/list+list)... what I would like to know is--

(1) Which of the above (or your own solution) will be easiest to manage- viz to store/fetch data (2) Which of the above will use the least amount of memory?

1
  • 2
    List is an interface, ArrayList is an implementation. List vs ArrayList does not make any sense as a comparison. You use List as the reference type unless you need a method specific to ArrayList. Commented Sep 6, 2012 at 20:11

3 Answers 3

1

I would declare my variable as:

List<List<DataType>> lists = new ArrayList<List<DataType>>();

There is a slight time penalty in accessing list methods through a variable of an interface type, but this, I think, is more than balanced by the flexibility you have of changing the type as you see fit. (For instance, if you decided to make lists immutable, you could do that through one of the methods in java.util.Collections, but not if you had declared it to be an ArrayList<List<DataType>>.)

Note that lists will have to hold instances of some concrete class that implements List<DataType>, since (as others have noted) List is an interface, not a class.

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

Comments

0

List is an interface. ArrayList is one implementation of List.

When you construct a List you must choose a specific concrete type (e.g. ArrayList). When you use the list it is better to program against the interface if possible. This prevents tight coupling between your code and the specific List implementation, allowing you to more easily change to another List implementation later if you wish.

1 Comment

I agree that programming against an interface is generally better. However, it's worth noting that in most VMs, there's a slight performance penalty in accessing methods of an object declared to be List as compared to declaring a concrete type.
0

If you know a way to identify which list you will be dealing with, use a map of lists.

Map<String,List<?>> = new HashMap<String,List<?>>();

This way you would avoid having to loop through the outer elements to reach the actual list. Hash map performs better than an iterator.

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.