[英]java arraylist of arraylists
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;
嗨,当我想要像矢量矢量这样的东西(元素当然要排序)我想到了arraylists的arraylist但是在C ++中我会这样做来访问元素v.at(i).at(j)=5;
and when i need to add new element v.at(i).push_back(value);
当我需要添加新元素v.at(i).push_back(value);
so how do i do this in java ? 那我怎么在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 ?? 因为我只能访问外部arraylist但我不知道如何添加新元素...并且有没有更好的方法来模拟java中的向量C ++向量?
ps (it's not a matrix 3*2 for ex but each arraylist may have different size) ps(前者不是矩阵3 * 2,但每个arraylist可能有不同的大小)
Declare an ArrayList
of ArraList<Integer>
s: 声明ArraList<Integer>
的ArrayList
:
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. 您可以在Java中使用List<List<Integer>>
。 accessing the element would be list.get(i).get(j)
. 访问该元素将是list.get(i).get(j)
。 Adding, likewise: list.get(i).add(var)
. 同样添加: list.get(i).add(var)
。 Also take a look at the set(..)
method 另请参阅set(..)
方法
I can't comment on previous comments yet so i'll post it here. 我还不能评论之前的评论,所以我会在这里发布。
As netbeans says it's not necessary to write 正如netbeans所说,没有必要写
ArrayList< ArrayList< Integer>> v = new ArrayList< ArrayList< Integer>>();
because the arguments are redundant; 因为论证是多余的; instead you can write: 相反,你可以写:
ArrayList< ArrayList< Integer>> v = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.