1、AbstractCollection类是提供Collection接口部分实现的便利类,除了size方法和iterator方法之外,它实现了Collection接口中的所有方法。
2、所有这些方法都返回boolean值,如果执行方法会改变这个集合,则返回true。
3、Iterator接口提供了对不同集合中的元素进行遍历的统一方法。
设计注意:Collection接口中的有些方法是不能在具体子类中实现的。在这种情况下,这些方法会抛出异常java.lang.UnsupportedOperationException,它是RuntimeException异常类的一个子类。如果一个方法在子类中没有意义,可以按如下方式实现它:
public void someMethod(){
throw new UnsupportedOperationException
(“Method not supported”);
}
探究Collection接口中的方法的例子
TestMethodInCollection.java
public class TestMethodsInCollection{
public static void main(String[] args){
//Create set1
java.util.Set set1 = new java.util.HashSet();
//Add strings to set1
set1.add("London");
set1.add("Paris");
set1.add("New York");
set1.add("San Francisco");
set1.add("Beijing");
System.out.println("set1 is " + set1);
System.out.println(set1.size() + " elements in set1");
//Delete a string from set1
set1.remove("London");
System.out.println("\nset1 is " + set1);
System.out.println(set1.size() + " elements in set1");
//Create set2
java.util.Set<String> set2 = new java.util.HashSet<String>();
//Add strings to set2
set2.add("London");
set2.add("Shanghai");
set2.add("Paris");
System.out.println("\nset2 is " + set2);
System.out.println("set2.size() + " elements in set2");
System.out.println("\nIs Taipei in set2? " + set2.contains("Taipei"));
set1.addAll(set2);
System.out.println("\nAfter adding set2 to set1, set1 is " + set1);
set1.removeAll(set2);
System.out.println("After removing set2 from set1, set1 is " + set1);
set1.retainAll(set2);
System.out.println("After removing common elements in set2 from set1, set1 is " + set1);
//
}
}
结果:
set1 is [San Francisco, New York, Paris, Beijing, London]
5 elements in set1
set1 is [San Francisco, New York, Paris, Beijing]
4 elements in set1
set2 is [Shanghai, Paris, London]
3 elements in set2
Is Taipei in set2? false
After adding set2 to set1, set1 is
[San Francisco, New York, Shanghai, Paris, Beijing, London]
After removing set2 from set1, set1 is
[San Francisco, New York, Beijing]
After removing common elements in set2 from set1, set1 is []