0

What is the best way of implementing an ArrayList that can store any level of ArrayLists within Arraylists and Integers.

List<List<Integer>> list = ArrayList<List>();

only allows up to 2 levels of lists within lists and doesn't allow for a mix of Intergers and ArrayLists.

This is some easy easy stuff in Python. And its a dumb data structure but unfortunately coding tests call for these sort of things.

  • Tried: List> list (or something similar? an Integer is an Object, so is an ArrayList – Stultuske Mar 20 '19 at 06:53
  • 2
    "This is some easy easy stuff in Python" other than the fact you don't know what the type of any given element is. You can easily create the same amount of confusion with a `List` in Java. – Andy Turner Mar 20 '19 at 06:56

2 Answers2

1

What is the best way of implementing an ArrayList that can store any level of ArrayLists within Arraylists and Integers

The only option you have List<Object> as Generics are compile-time properties. So you can't dynamically change/decide the type depending upon the runtime data.

So, the best and only option I believe List<Object>. However, you may need to cast many times to use that list.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42
  • Probably `List extends Object>` is better, as it properly signals the intent to take subclasses of Object in. – Ferrybig Mar 20 '19 at 07:18
  • 3
    @Ferrybig no, because you then couldn't put anything other than literal null into it. (And that would be the same as `List>` anyway) – Andy Turner Mar 20 '19 at 07:19
  • A tonne of casts to get to any particular level of the structure by the looks of it. May have to rethink this entirely. – user8482543 Mar 20 '19 at 08:57
0

The only way to do this in a more type-safe way than List<Object> is to define a union type:

class IntegerOrList {
  final Integer i;
  final List<IntegerOrList> list;

  // Constructors to ensure that only one of i and list is present.
  IntegerOrList (Integer i) {
    this.i = i; this.list = null;
  }

  IntegerOrList (List<IntegerOrList> list) {
    this.i = null; this.list = list;
  }

  // Getters.
}

This should throw or otherwise handle if you try to access the absent one.

Then create a list of these:

List<IntegerOrList> list = new ArrayList<>();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243