-1

How to create a 2D ArrayList<ArrayList<String>> like

competition = [["A", "B"], 
["B", "C"],
["C", "A"]]

how can I declare it initialized during declaration? or the only way to do it as following

 ArrayList<ArrayList<String>> competitions = new ArrayList<>();

        ArrayList<String> x = new ArrayList<>();
        x.add("A");
        x.add("B");

        ArrayList<String> y = new ArrayList<>();
        y.add("B");
        y.add("C");

        ArrayList<String> z = new ArrayList<>();
        z.add("C");
        z.add("A");

competitions.add(x);
competitions.add(y);
competitions.add(z);

MvsW
  • 97
  • 1
  • 11
  • `ArrayList` is a class like any other. Unlike arrays, it doesn't have a short-hand literal representation. But you could make a 2d-array and then [convert it to an `ArrayList`](https://stackoverflow.com/questions/11447780/convert-two-dimensional-array-to-list-in-java) – Federico klez Culloca Apr 29 '21 at 07:29

2 Answers2

1

You can use something like that if I understand your need:

List<List<String>> list = Arrays.asList(
           Arrays.asList("A", "B"),
           Arrays.asList("B", "C"),
           Arrays.asList("C", "A")
);

EDIT:

List<List<String>> list = new ArrayList<>(Arrays.asList(
            new ArrayList<>(Arrays.asList("A", "B")),
            new ArrayList<>(Arrays.asList("B", "C")),
            new ArrayList<>(Arrays.asList("C", "A"))
));
M. Dudek
  • 978
  • 7
  • 28
0

If I understand well you are trying to create an arrayList from an Array ou can do it with

new ArrayList<>(Arrays.asList(array));
h4kcr0o
  • 1
  • 3
  • No, below doesn't work **ArrayList<> c2 = new ArrayList<>(Arrays.asList("A", "B"), Arrays.asList("B", "C"));** – MvsW Apr 29 '21 at 07:56
  • Because this is not an array you should type something like : ArrayList<> c2 = new ArrayList<>(Arrays.asList(["A", "B"]) you missed '[' – h4kcr0o Apr 29 '21 at 08:51
  • Didn't work **ArrayList> c2 = new ArrayList<>(Arrays.asList(["A", "B"]);** – MvsW Apr 29 '21 at 17:18