Q 16:谈谈你对Java Collections Framework的理解? LF DP FAQ
Q 16:
collections framework对外提供的接口是List,Set and Map.List和Set继承自Collection接口.不要把Collection这个接口和Collections这个类搞混了,这个Collections类与Arrays类似,也是一个工具类.
Set(HashSet,TreeSet):
在Set我们不能放入重复的元素,HashSet和TreeSet是这个接口的两个实现类,TreeSet是一个有序的HashSet,这个类实现了SortedSet接口.
List(ArrayList,LinkedList,Vector etc):
List是一个有序的collection,它里面可以放入重复的元素.ArrayList,LinkedList和Vector三个类都是List接口的实现类.
Collections API同时也支持maps,但并不在Collection接口所在类hierarchy.在Java中,Map描述的是这样一个对象,它将keys映射到values,这里的list of keys本身是就是一个Collection object.Map中可以包含重复的values,不过map中的keys必须互异.HashMap,TreeMap和Hashtable都是Map接口的实现类.TreeMap是一个有序的HashMap,它实现了SortedMap接口.
Q. 怎么来实现有序的collection? SortedSet和SortedMap两个接口可以maintain sorted order.Comparable接口的实现类impose natural order(这个natural ordering是什么意思?与这里的SortedMap和SortSet有什么关系?这两个SortedSet和SortedMap两个接口与Comparable又有什么关系?在sort方法里会调用natural ordering的特性?).通过实现Comparable接口,排序一个array of objects或一个collection(List etc)可以像下面代码所示那样简单:
Arrays.sort(myArray);
Collections.sort(myCollection);//这里的myCollection实现了Comparable接口么?
若一个类没实现Comparable接口,或想可以按multiple attributes来排序,我们要用Comparator接口.
Comparable接口:
1,利用Comparable接口可以比较其实现类与别的相似对象(i.e. A class that implements Comparable becomes an object to be compared with).Comparable里有compareTo()这个方法需要实现.
2,Java类库中像String,Integer,Date,File等这样的standard类都实现Comparable接口,从而就用了"Natural Ordering".例如,String类用下面的方法:
public int compareTo(o)
public int compareToIgnoreCase(str)
在自写类中也可以如下所示地实现Comparable接口
...imports
public class Pet implements Comparable {
int petId;
String petType;
public Pet(int argPetId,String argPetType) {
petId = argPetId;
this.petType = argPetType;
}
public int compareTo(Obejct o){
Pet petAnother (Pet) o;
//natural alphabetical ordering by type
return this.petType.compareTo(petAnother.petType);
}
public static void main(String[] args){
List list = new ArrayList();
list.add(new Pet(2,"Dog"));
list.add(new Pet(1,"Parrot"));
list.add(new Pet(2,"Cat"));
Collections.sort(list); // sorts using compareTo method
for(Iterator it = list.iterator();it.hasNext();){
Pet e = (Pet) it.next();
System.out.println(e);
}
}
public String toString(){
return petType;
}
}
Output: Cat, Dog, Parrot.
Comparator interface:
1,利用Comparator接口可以比较两个不同类型的对象.Comparator里有以下的方法需要实现:
public int compare (Object o1, Object o2)
2,通过自写Comparator类,我们就可以有更多的关于排序的控制.下面我们用Comparator来重写Pet类的排序.For most cases natural ordering is fine(这就是前面所说的sort方法里所提到的natural ordering了,哈哈...明白了!!!),but say we require a special scenario where we need to first sort by the "petId" and then by "petType".We can achieve this by writting a "Comparator" class.
...imports
public class PetComparator implements Comparator,Serializable{
public int compare(Object o1, Object o2){
int result = 0;
Pet pet = (Pet) o1;
Pet petAnother = (Pet)o2;
//use Integer class's natural ordering
Integer pId = new Integer(pet.getPatId());
Integer pAnotherId = new Integer(petAnother.getPetId());
result = pId.compareTo(pAnotherId);
//if ids are same compare by petType
if(result ==0){
result = pet.getPetType().compareTo(petAnother.getPetType());
}
return result;
}
public static void main (String[] args) {
List list = new ArrayList();
list.add(new Pet(2,"Dog"));
list.add(new Pet(1,"Parrot"));
list.add(new Pet(2,"Cat"));
Collections.sort(list,new PetComparator());
for(Iterator it = list.iterator();it.hasNext();){
Pet e = (Pet) it.next();
System.out.println(e);
}
}
public String toString(){
return petType;
}
}
Output: Parrot,Cat,Dog.
Important: The ordering imposed by a java.util.Comparator "myComp" on a set of elements "mySet" should be consisent with equals() method,which means for example:
if compare(o1,o2) ==0 then o1.equals(02) should be true.
if compare(o1,o2) !=0 then o1.equalt9o2) should be false.
If a comparator "myComp" on a set of elements "mySet" is inconsistent with equals() method, then SortedSet or SortedMap will behave strangely and is hard to debug.(这仅仅是一种编程约定,那在语言层面上没有对此的限定么?似乎有不妥的地方吧,最好是能在编译器层面上对这个的检查.)例如,if you add two objects o1, o2 to a TreeSet (implements SortedSet) such that o1.equals(o2) == true and compare(o1,o2) != 0 the second add operation will return false and will not be added to your set because o1 and o2 are equivalent from the TreeSet’s perspective. 若我们想往TreeSet添加两个对象(o1和o2),而这个对o1和o2来说o1.equals(o2)为true并且compare(o1,o2) !=0的话,对TreeSet添加第二个元素就会返回false,这个添加也不会成功,由于这里的o1和o2在TreeSet看来并不相等.(噢,这个add的方法返回false有很大的作用呀!以前可是没有注意过这事,这样也就弥补了前面所说的"编译器层面检查"上的不足.以后往TreeSet里通过调用add方法添加Object时可得check这个的返回值是否为false!!!).
Design Pattern:
Q. What is an Iterator? An Iterator is a use once object to access the objects stored in a collection.Iterator design pattern is used, which is a behaviroal design pattern that provides a way to access elements of a collection sequentialy without exposing its internal representation.(呵呵,这个Iterator现在也理解多了,对Java的伟大也更为敬重了!)
Q. why do you get a ConcurrentmodificationException when using an iterator? CO