Alex Rivera | Logout

What collection to use instead of 2D array in Java?

Asked 2010-01-12T16:31:18.330
16

I want to use a collection in place of 2D array so that I don't need to give its size at the time of declaration and I can add as many elements as I want dynamically.

Edit
Report

2 Answers

4

The easiest way is to use nested collections... say (assuming your values are Strings) List<List<String>> which can then be used like this:

List<List<String>> fakeArray = new ArrayList<List<String>>();

// Pretend you fill it with values between these calls
String retrieve = fakeArray.get(0).get(0);

Edit: This was originally a Map<String,List<String>> which really doesn't make sense in this context.

However, you may want to see if Google Collections or Apache Commons Collections have something more specialized that you can use.

answered 2010-01-12T16:34:31.587
0

I'm personally using the Vector class for that purpose, though different requirements may eventually dictate the use of other, more specialized classes.

answered 2010-01-12T16:33:37.093

Your Answer