Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacking generics

Tags:

java

generics

Is this bad practice?

ArrayList<ArrayList<ArrayList<Double>>> list = new ArrayList<ArrayList<ArrayList<Double>>>();
like image 984
rhombidodecahedron Avatar asked Jul 14 '10 15:07

rhombidodecahedron


4 Answers

It is a three-dimensional matrix based on ArrayList. Doesn't look nice, but that's how we have to write it.

An alternative could be:

List<List<List<Double>>> list = new ArrayList<List<List<Double>>>();

which is a bit shorter and usually OK as in most cases your just interested in the interface methods.

So if you need a resizable threedimensional matrix data structure, then this is a clean approach.

like image 139
Andreas Dolk Avatar answered Sep 28 '22 00:09

Andreas Dolk


This is not necessarily bad practice. It's just "unreadable". Have a bit of patience, in the upcoming Java 7 you're allowed to omit the cruft in specific generic types when constructing the parameterized type:

List<List<List<Double>>> list = new ArrayList<>();

This is called type inference.

As of now, if you can live with compiler warnings, you can also just do so:

List<List<List<Double>>> list = new ArrayList();
like image 35
BalusC Avatar answered Sep 27 '22 23:09

BalusC


It would probably be a good idea to create a new class to handle the behavior you are trying to accomplish. I would create a class that uses an private ArrayList<...> (favor delegation over inheritance) and create necessary methods. If anything it should make things easier to read and understand.

like image 27
Jerod Houghtelling Avatar answered Sep 27 '22 23:09

Jerod Houghtelling


yes. most likely your code is better off with double[][][]

like image 35
irreputable Avatar answered Sep 27 '22 23:09

irreputable