-2

Not sure if this is commonly used, because I have seen Array grid.

List<Object> LL1 = new ArrayList<>(Arrays.asList(1, 2));
List<Object> LL2 = new ArrayList<>(Arrays.asList(4, 5, 6));
List<Object> LL3 = new ArrayList<>(Arrays.asList(7, 8, 9));
List<Object> Lgrid = new ArrayList<>(Arrays.asList(LL1, LL2, LL3));
System.out.println(Lgrid);  // >>> [[1, 2], [4, 5, 6], [7, 8, 9]]

So I create a ArrayList grid, no problem. Now, if I want to add a value into 1st element of the grid, (LL1).

// I can:
LL1.add(3);
// But I can't:
Lgrid.get(0).add(3);

I believe if it is an Array grid, I can do this, at least edit by calling Array[0][0] = newValue.

Is there anyway for me to just handle things from the grid?

Thanks!

jxie0755
  • 1,682
  • 1
  • 16
  • 35
  • `LL1.add(3);` this will throw Exception in thread "main" java.lang.UnsupportedOperationException – Ryuzaki L Mar 07 '19 at 21:34
  • 1
    *"But I can't: `Lgrid.get(0).add(3)`" ... you could if you would stop using raw types. – Tom Mar 07 '19 at 21:34
  • @Deadpool Why should it? – Tom Mar 07 '19 at 21:34
  • `Arrays.asList()` will return unmodifable list https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList-T...- – Ryuzaki L Mar 07 '19 at 21:35
  • 1
    @Deadpool Cool and then pass that unmodifiable list into the `ArrayList` constructor and you get? ... a modifiable list :) – Tom Mar 07 '19 at 21:36
  • Code_Control, about your edit: why do you want to shot yourself in to the foot? Why do you use `List`? You __want__ to interact with the inner list and still trick Java into believing it is just an ordinary object? Why? – Tom Mar 07 '19 at 21:39
  • guys, I added all `` back, didn't know that it could impact. But the answer pointed out that I should use `List`, and that solves the problem! Thank you all. – jxie0755 Mar 07 '19 at 21:40
  • @Tom That was a mistake. I am new to the java world, from python...so I tend to forget about the importance of claiming the types in java. – jxie0755 Mar 07 '19 at 21:41
  • 1
    Please don't just use `List`, that still uses raw types. Use `List>` and always add the _correct_ generic types, not just half and not just ``. That gives you type safety and less headaches. – Tom Mar 07 '19 at 21:42
  • 1
    @Tom Thank you. Lesson learned. – jxie0755 Mar 07 '19 at 21:49

1 Answers1

3

You need to make the List of lists a specific type:

List<List> Lgrid = new ArrayList<>(Arrays.asList(LL1, LL2, LL3));

Edit: Better practice to use non-raw types:

    List<Integer> LL1 = new ArrayList<>(Arrays.asList(1, 2));
    List<Integer> LL2 = new ArrayList<>(Arrays.asList(4, 5, 6));
    List<Integer> LL3 = new ArrayList<>(Arrays.asList(7, 8, 9));
    List<List<Integer>> Lgrid = new ArrayList<>(Arrays.asList(LL1, LL2, LL3));
    Lgrid.get(0).add(3);
Harvey Ellis
  • 596
  • 1
  • 3
  • 12