It looks like you’ve confused yourself by adding arrays to lists. This effectively gives you another “layer”: You’ve got the list (l
or l1
), which contains an array, which contains some strings. The problem is you’re thinking of the lists as if they contained strings, when they do not. Let me comment your code to show where this got introduced:
// 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));
We can clear up a lot of confusion by eliminating this “middle layer.” Below is an example of how you could add the strings directly to the list:
// 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]
When you add the elements directly to the list as shown above, you get the behavior you describe in the question.
solved How to clear one list with values from another