Collection 是 - 数据集合。这是任何类型的集合(列表、地图、树...)的基本接口。任何集合都是(或应该是)Iterable,这意味着您可以遍历集合的所有元素(例如,在循环中)。
List 显然也是一个集合,因为列表是数据的集合。这就是 List 接口扩展 Collection 接口的原因。
但是,由于实现 List 的方法有很多,因此 List 只是一个接口而不是一个类。 ArrayList 通过包装一个数组来实现一个列表。另一个例子是LinkedList,它通过将元素相互链接来存储数据。我不想讨论它们的优缺点(你可以查一下)。
最后要考虑的是,您存储在集合(列表)中的数据具有类型。通常,您只会在特定集合中存储一种类型的 Object,这就是 Collection 接口(及其所有子接口,如 List)采用类型参数的原因。此参数指定您希望存储在列表中的数据类型,这有利于类型安全和方便。
现在,在您的代码中:
List<String> list = new ArrayList<String>();
List<String> removeList = new ArrayList<String>();
您创建了一个名为“list”的变量。这个变量的类型是List,意思是:一个字符串列表。使用 new 运算符,您可以创建实际对象。显然,您必须选择一个实现,并且您选择了“ArrayList”。自然,您希望集合中包含字符串,因此您将字符串指定为类型参数。由于您正在调用 ArrayList 的构造函数,因此您需要空括号(因此您调用不带任何参数的构造函数)。
第二行代码也是如此。
//this method takes two collections
//that means that you can pass any type of collection (including list) to it
//the advantage is that you could also pass another type of collection if you chose to do so
private void removeColors(Collection<String> collection1,Collection<String> collection2)
{
Iterator<String> iterator = collection1.iterator();//this line takes the iterator of your first collection
//an iterator is an object that allows you to go through a collection (list)
//you can get the objects one by one by calling the next() method
while(iterator.hasNext())//basically, that's what you're doing here:
//you let the loop continue as long as there are more items inside the iterator, that is, the first collection
if(collection2.contains(iterator.next()))//so if there's another item, you take it by calling next() and check if the second collection contains it
iterator.remove();//if that's the case, you remove the item from the first collection
}
//what you've basically achieved:
//you removed all the items from the first collection that you can find in the second collection as well, so you could say:
//collection1 = collection1 - collection2
现在,您可以用数据(字符串)填充您在上面创建的字符串列表,并对 removeList 执行相同操作,然后通过调用从列表中“减去”removeList:
removeColors(list, removeList);