Collection.retainAll() works oddly

时间:2017-06-09 12:55:49

标签: java

I currently have a problem with the function .retainAll(). The purpose is to find the tokens that are stored in sortedTXT.

Here is my code:

List<String> sortedTXT = new ArrayList<>();
List<String> tokens = new ArrayList<>();

// Some code 

sortedTXT.add(String someString);
tokens.add(String someString);

// Some code

System.out.println(tokens.size());
System.out.println(sortedTXT.size());

Collection<String> listTerms = sortedTXT;
   listTerms.retainAll(tokens);

System.out.println(tokens.size());
System.out.println(sortedTXT.size());
System.out.println(listTerms.size());

And here is the output. I don't understand why sortedTXT has been modified because I cast it into the listTerms to avoid any modifications on it. I tried also to declare listTerms as a Listrather as a Collection. But I still get the same problem.

It is normal that listTerms is empty because none terms of sortedTXT is among the tokens. There is no Exception at all.

19
3

19
0
0

0 个答案:

没有答案