Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any efficient 2D ArrayList classes for Java?

I know that it's possible to create a 2D ArrayList with ArrayList<ArrayList<E>>, but that is cumbersome and a real casting nightmare when it comes to adding and retrieving objects.

Are there any 2D ArrayList classes that do this sort of thing more efficiently? I am writing a true 2D ArrayList class from the ground up, and I'm wondering if there is anyone else who has done this sort of thing in an efficient manner.

like image 995
Nick Anderegg Avatar asked Mar 10 '11 22:03

Nick Anderegg


People also ask

Can you make a 2D ArrayList in Java?

The following article provides an outline for 2D ArrayList in Java. In java array list can be two dimensional, three dimensional etc. The basic format of the array list is being one dimensional. Apart from one dimensional all other formats are considered to be the multi-dimensional ways of declaring arrays in java.

Is there a 2D ArrayList?

Two-Dimensional ArrayList In addition, let's assume there are 3 edges in the graph (0, 1), (1, 2), and (2, 0), where a pair of vertices represents an edge. We can represent the edges in a 2-D ArrayList by creating and populating an ArrayList of ArrayLists.

Is ArrayList efficient Java?

ArrayList is a highly optimized and very efficient wrapper on top of a plain Java array. A small timing overhead comes from copying array elements, which happens when the allocated size is less than required number of elements.

Can a 2D array have different data types Java?

You can have multiple datatypes; String, double, int, and other object types within a single element of the arrray, ie objArray[0] can contain as many different data types as you need. Using a 2-D array has absolutely no affect on the output, but how the data is allocated.


2 Answers

no, unfortunately there isn't 2d ArrayList class. your alternative options are (in case 0/1/2 of the Diamension is constant):

MyType[][] myList = new MyType[n][m];

or

ArrayList<MyType>[] myList = new ArrayList<MyType>[n];

or

ArrayList<ArrayList<MyType>> myList = new ArrayList<ArrayList<MyType>>();

another option is to save all your data in 1d ArrayList and create a function that recieve (x,y) and return the place x in the ArrayList. this way you demonstrate outside a 2d array, but save the elements easily in 1d ArrayList

like image 195
Aviv A. Avatar answered Nov 05 '22 20:11

Aviv A.


Using the "ArrayList>" type approach is fine and pretty standard for this kind of thing from what I have seen. You can easily write a 2D array list class that provides convenience methods for adding / removing items, etc, and it will be far from "cumbersome" or "a casting nightmare" to use this. Have a look at this implementation as an example. It is not quite perfect but it illustrates how easy it is to use this kind of approach.

like image 42
brent777 Avatar answered Nov 05 '22 21:11

brent777