解释甲Collection是 - 数据的集合。这是任何类型集合(列表,地图,树,...)的基础接口。任何集合都是(或应该是)Iterable,这意味着您可以迭代集合的所有元素(例如,在循环中)。
A List显然也是一个集合,因为列表是数据的集合。这就是List接口扩展Collection接口的原因。
但是,由于有很多方法来实现List,List仅仅是一个接口而不是一个类。 ArrayList通过包装数组来实现一个列表。另一个例子是LinkedList,它通过将元素彼此链接来存储数据。我不想讨论它们的优点和缺点(正如你可以查看它们一样)。
最后要考虑的事实是,您存储在集合(列表)中的数据有一个类型。通常,你只会在一个特定的集合中存储一种类型的Object,这就是为什么Collection接口(和它的所有子接口如List)都有一个类型参数的原因。此参数指定您想要存储在列表中的数据类型,这对于类型安全性和方便性很有好处。
现在,在你的代码:
List<String> list = new ArrayList<String>();
List<String> removeList = new ArrayList<String>();
您创建一个名为 “清单” 的变量。这个变量的类型是List <字符串>,这意味着:一个字符串列表。使用新的操作符,可以创建实际的对象。显然,你必须选择一个实现,并且你选择了“ArrayList”。当然,你需要在你的集合中使用字符串,所以你需要指定String作为类型参数。既然你调用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);
其编译时间类型的安全性,所以你不会添加别的东西只有字符串 – Adi 2014-08-27 11:12:48
括号是需要的,因为你调用的方法(构造函数) – munyul 2014-08-27 11:15:26
你应该阅读一些基本的教程,然后再提问题。请参阅java中的泛型 – 2014-08-27 11:15:56