[英]How do I remove an entry out of a ArrayList
I have an ArrayList which is like this;我有一个像这样的 ArrayList;
int a=0;
int b=0;
int c=4;
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(a);
al.add(b);
al.add(c);
I would like to remove all entries which have the value 0
, and become the int c
with value 4
to be at index 0
.我想删除所有值为
0
条目,并成为值为4
的int c
位于index 0
。
How can I do that?我该怎么做?
This should work:这应该有效:
for (int i = 0; i < al.size(); i++) {
if (al.get(i) == 0) {
al.remove(i);
i--;
}
}
Java 8 流方式,虽然可能不适合您(不使用 Java 8,老师没有寻找这种确切的方式等)
al.removeIf(a -> a == 0);
Get an Iterator
from the List
, iterate it and call Iterator.remove()
if the value retrieved is 0
.从
List
获取一个Iterator
,对其进行迭代并在检索到的值为0
调用Iterator.remove()
。 Something like,类似的东西,
int a = 0, b = 0, c = 4;
List<Integer> al = new ArrayList<>(Arrays.asList(Integer.valueOf(a), b, c));
Iterator<Integer> iter = al.iterator();
while (iter.hasNext()) {
if (iter.next() == 0) {
iter.remove();
}
}
System.out.println(al);
Output is (because 4
is element 0 as requested)输出是(因为
4
是请求的元素 0)
[4]
Arraylist has a method called remove(index i) Arraylist 有一个方法叫做 remove(index i)
It is also has a method called set(index i, element e)它还有一个方法叫做 set(index i, element e)
So you would create a loop for the size of the arraylist, check if the value is 0 and if it is call the remove method.因此,您将为数组列表的大小创建一个循环,检查该值是否为 0 以及是否调用 remove 方法。
If you want to set the value of index 0 to 4 then use the set method but don't do it in the loop because then it will execute multiple times which is inefficient programming.如果要将索引 0 的值设置为 4,则使用 set 方法,但不要在循环中进行,因为这样会执行多次,这是低效的编程。
I assume this is homework so I won't give the answer.我认为这是家庭作业,所以我不会给出答案。 Go https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html and look at the Add, Get, and Remove methods.
转到https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html并查看 Add、Get 和 Remove 方法。 Those methods provide the functionality that you're looking for.
这些方法提供了您正在寻找的功能。
Try this:试试这个:
for(int i=0;i<al.size();i++){
if(al.get(i)==0){
al.remove(i);
i--;
}
}
List<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(0);
al.add(4);
List<Integer> modAl = new ArrayList<Integer>();
Collections.sort(al);
for (int i : al) {
if (i != 0 ) {
modAl.add(i);
}
}
Collections.sort(modAl, Collections.reverseOrder());
al = modAl;
System.out.println(al);
OUTPUT:输出:
[4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.