如何用另一个列表中的值清除一个列表

How to clear one list with values ​from another

不要告诉我如何修复这段代码,有两个lists.I需要从第二个清除一个,但是当执行删除方法时,没有任何作用。

List<String[]> l = new ArrayList<>();
List<String[]> l1 = new ArrayList<>();
final String s = "a,b,c";
final String s1 = "a,b,c,d";

l.add(s.split(",", -1));
l1.add(s1.split(",", -1));

System.out.println(Arrays.asList(l.get(0)));        //[a, b, c]
System.out.println(Arrays.asList(l1.get(0)));       //[a, b, c, d]

System.out.println(l.removeAll(l1));                //false

如果我这样做

 System.out.println(l.retainAll(l1));                //true

然后一个列表被完全清除。删除后想得到类似[d]

的东西

您似乎对向列表中添加数组感到困惑。这有效地为您提供了另一个“层”:您已获得列表(ll1),其中包含一个数组,其中包含一些字符串。问题是您将列表视为好像它们包含字符串,而实际上它们不包含字符串。让我评论你的代码以显示它是在哪里引入的:

// String[] is an array of strings
// List<String> is a list of strings
// List<String[]> is a list of arrays of strings
List<String[]> l = new ArrayList<>();
List<String[]> l1 = new ArrayList<>();

final String s = "a,b,c";
final String s1 = "a,b,c,d";

// s.split(",", -1) returns an array of strings
// You then add this array to your list of arrays
l.add(s.split(",", -1));
l1.add(s1.split(",", -1));

// This shows the strings because of the Arrays.asList() call
// l.get(0) returns the array from the list, then Arrays.asList()
// converts that array to a new list, which prints out nice and pretty
System.out.println(Arrays.asList(l.get(0)));
System.out.println(Arrays.asList(l1.get(0)));

// Here, you are trying to remove the array stored in l1 from l
// l doesn't contain the array stored in l1, it has a different array
// So nothing happens
System.out.println(l.removeAll(l1));

我们可以通过消除这个“中间层”来消除很多困惑。以下是如何将字符串直接添加到列表中的示例:

// Type is List<String>
List<String> l = new ArrayList<>();
List<String> l1 = new ArrayList<>();

final String s = "a,b,c";
final String s1 = "a,b,c,d";

// We need to convert the arrays to lists using Arrays.asList()
// prior to calling addAll()
l.addAll(Arrays.asList(s.split(",", -1)));
l1.addAll(Arrays.asList(s1.split(",", -1)));

// We can print the lists out directly here, rather than
// messing with converting arrays
System.out.println(l);                       // [a, b, c]
System.out.println(l1);                      // [a, b, c, d]

System.out.println(l1.removeAll(l));         // true
System.out.println(l1);                      // [d]

如上所示将元素直接添加到列表中时,会出现问题中描述的行为。