gpt4 book ai didi

java - 删除pojo数组列表项

转载 作者:行者123 更新时间:2023-11-30 07:27:00 24 4
gpt4 key购买 nike

当 pojo 类 arraylist 项等于 arraylist 字符串时,我需要删除它。

下面我发布了代码:

示例.java:

import java.util.ArrayList;

public class Sample {

public static void main(String args[]) {

ArrayList<String> arrStr;

ArrayList<Student> arrStudent;

arrStr = new ArrayList<String>();

arrStudent = new ArrayList<Student>();


arrStr.add("100");
arrStr.add("150");
arrStr.add("200");
arrStr.add("250");
arrStr.add("300");

arrStudent.add(new Student("Max", "Get Data ", "140"));
arrStudent.add(new Student("Max", "Get Data ", "150"));
arrStudent.add(new Student("Max", "Get Data ", "160"));
arrStudent.add(new Student("Max", "Get Data ", "200"));
arrStudent.add(new Student("Max", "Get Data ", "230"));


for (String item : arrStr) {

System.out.println("item :" +item);

System.out.println("ArrListCheck" +arrStudent.toString());


if (arrStudent.contains(item)) {

arrStudent.remove(item);

} else {

System.out.println("Else Called");


}
}

}

}

Student.java:

public class Student {

public String name;

public String description;

public String id;

public Student(String name, String description, String id) {
this.name = name;
this.description = description;
this.id = id;
}

public String getName() {
return name;
}

public String getDescription() {
return description;
}

public String getId() {
return id;
}

@Override
public String toString() {

String str = name +""+description+""+id;

return str;
}

}

输出:

item :100
ArrListCheck[MaxGet Data 140, MaxGet Data 150, MaxGet Data 160, MaxGet Data 200, MaxGet Data 230]
Else Called

item :150
ArrListCheck[MaxGet Data 140, MaxGet Data 150, MaxGet Data 160, MaxGet Data 200, MaxGet Data 230]
Else Called

item :200
ArrListCheck[MaxGet Data 140, MaxGet Data 150, MaxGet Data 160, MaxGet Data 200, MaxGet Data 230]
Else Called

item :250
ArrListCheck[MaxGet Data 140, MaxGet Data 150, MaxGet Data 160, MaxGet Data 200, MaxGet Data 230]
Else Called

item :300
ArrListCheck[MaxGet Data 140, MaxGet Data 150, MaxGet Data 160, MaxGet Data 200, MaxGet Data 230]
Else Called

正如您在上面的代码中看到的,它总是调用 else。我不知道如何将 arraylist 字符串中的两个 id 与 arraylist pojo 类相等,然后我必须根据 id 删除 arraylist pojo 类项目。任何人可以帮我解决这个问题。

最佳答案

您可以迭代 ArrayList<Student>而不是迭代 ArrayList<String> :

    for (int i = 0; i < arrStudent.size(); i++) {
Student student = arrStudent.get(i);
if (arrStr.contains(student.getID())) {
arrStudent.remove(i);
i--;
} else {
System.out.println("Else Called");
}
}

关于java - 删除pojo数组列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com