hi when I wanted to have something like vector of vectors (elements shall be ordered of course) I thought of having arraylist of arraylists but in C++ i would do this to access the element v.at(i).at(j)=5;
and when i need to add new element v.at(i).push_back(value);
so how do i do this in java ? because I can only access the outer arraylist but i don't know how to add new elements...and is there a better way to simulate C++ vector of vectors in java ??
ps (it's not a matrix 3*2 for ex but each arraylist may have different size)
Declare an ArrayList
of 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
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);
You can have List<List<Integer>>
in Java. accessing the element would be list.get(i).get(j)
. Adding, likewise: list.get(i).add(var)
. Also take a look at the set(..)
method
I can't comment on previous comments yet so i'll post it here.
As netbeans says it's not necessary 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<>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.