我在一个列表中有一个整数 1,2,3,4 的列表,称为 a1temp,并且想要使用 GA 中的项目来删除 a1temp 中的相同项目,使用 a1temp.removeAll(GA);
基本上, 获取列表 A 中的项目列表 想要删除列表 B 中的相同项目
所以我得到了我的代码
如果有任何可能的帮助,我将不胜感激。预先感谢
显然,导入一些东西,导入 java.util.ArrayList;导入 java.util.List;
class R{
List<Integer> GA = new ArrayList<Integer>();
List<Integer> a1temp = List.of(1, 2, 3, 4);
int a1 = 0;
int a2 = 0;
int a3 = 0;
int a4 = 0;
//如果a1不为0(有另一个值)并且它还没有在GA中,则会检查它的值并将其添加到GA中。
public void checkGA() {
if (a1 != 0) {
if (!GA.contains(a1)) {
GA.add(a1);
}}}
// 将 listA 中的项目与 listB 中的项目一起删除。
public void placeGA() {
// Check if GA has some value.
if (GA.size() > 0) {
try {
//Here is where the problem appears.
// "a1temp list" should be getting the items removed
// when "a1temp" has same items as "GA list"
a1temp.removeAll(GA);
}catch (Exception e){
System.out.println("Can't delete");
}}}
public class Main {
public static void main(String[] args) {
R r1 = new R();
r1.a1 = 4;
r1.a2 = 3;
r1.a3 = 2;
// We add items from a1, a2 & a3 to GA list
r1.checkGA();
System.out.println("Show GA");
// Shows current items in GA list
System.out.println(r1.GA);
控制台:
显示GA
[4,3,2]
System.out.println("show a1temp);
// defined before a1temp = List.of(1, 2, 3, 4);
System.out.println(r1.a1temp);
控制台:
显示 1 个温度
[1,2,3,4]
// try to delete items 2, 3, 4.
r1.placeGA();
}
控制台 无法删除。
错误显示: 错误:
线程“main”中的异常 java.lang.UnsupportedOperationException 在 java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) 在 java.base/java.util.ImmutableCollections$AbstractImmutableCollection.removeAll(ImmutableCollections.java:151) 在 R.placeGA(Main.java:124) 在 Main.main(Main.java:255)
所以我尝试从 a1temp 中删除项目 2、3、4,这样它只会显示列表中的项目 1。
谁能告诉我为什么不起作用?
提前致谢。这是我的第一篇文章。
尝试从一个列表中删除第 2、3、4 项,但出现错误。
List.of 创建一个不可变列表,因此在
removeAll
上使用 UnsupportedOpration。
一种简单的方法是使用
ArrayList
构造函数,该构造函数将另一个列表作为参数:
List<Integer> a1temp = new ArrayList<Integer>(List.of(1, 2, 3, 4));