Java arraylist arraylists

hi, when I wanted to have something like a vector of vectors (elements should be ordered, of course), I thought about having arraylist arraylists, but in C ++ I would do this to access the element v.at(i).at(j)=5;, and when I need to add a new element v.at(i).push_back(value); so how can i do this in java? because I can only access the external arraylist, but I don’t know how to add new elements ... and is there a better way to simulate a vector of C ++ vector vectors in java ??

ps (this is not a 3 * 2 matrix for ex, but each arraylist may have a different size)

+3
source share
4 answers

ArrayList ArraList<Integer> s:

ArrayList<ArrayList<Integer>> v = new ArrayList<ArrayList<Integer>>();
v.add(new ArrayList<Integer>());

v.get(0).add(new Integer(5));
v.get(0).add(new Integer(10));
System.out.println(v.get(0).get(0)); // => 5
System.out.println(v.get(0).get(1)); // => 10
+7
List<List<Integer>> l = new ArrayList<List<Integer>>();

// initialize the inner lists
for (int i = 0; i < 10; i++) 
    l.add(new ArrayList<Integer>());


// now you can use it as you would like
l.get(i).add(5);
l.get(i).set(0, 3);
+4

In Java maybe List<List<Integer>>. access to the item will be list.get(i).get(j). Adding also: list.get(i).add(var). Also take a look at the methodset(..)

+1
source

I cannot comment on previous comments, so I will post it here.

Because netbeans says no need to write

ArrayList< ArrayList< Integer>> v = new ArrayList< ArrayList< Integer>>();

because the arguments are redundant; instead you can write:

ArrayList< ArrayList< Integer>> v = new ArrayList<>();
0
source

Source: https://habr.com/ru/post/1774670/


All Articles