在看到set这部分了,书中说set为了防止元素的重复,必须得为元素定义equals()方法,但是,给的例子确实这样的: //: c11:Set2.java
// Putting your own type in a Set.
import com.bruceeckel.simpletest.*;
import java.util.*;public class Set2 {
private static Test monitor = new Test();
public static Set fill(Set a, int size) {
for(int i = 0; i < size; i++)
a.add(new MyType(i));
return a;
}
public static void test(Set a) {
fill(a, 10);
fill(a, 10); // Try to add duplicates
fill(a, 10);
a.addAll(fill(new TreeSet(), 10));
System.out.println(a);
}
public static void main(String[] args) {
test(new HashSet());
test(new TreeSet());
test(new LinkedHashSet());
monitor.expect(new String[] {
"[2 , 4 , 9 , 8 , 6 , 1 , 3 , 7 , 5 , 0 ]",
"[9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ]",
"[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]"
});
}
} ///:~该例子把MyType 这种类型的元素放入set中,mytype是书中前面定义的,只是实现了comparable接口的compareTo()方法, 没有定义equals().
这是不是说equals()方法可以用comparable接口的compareTo()方法来代替?
// Putting your own type in a Set.
import com.bruceeckel.simpletest.*;
import java.util.*;public class Set2 {
private static Test monitor = new Test();
public static Set fill(Set a, int size) {
for(int i = 0; i < size; i++)
a.add(new MyType(i));
return a;
}
public static void test(Set a) {
fill(a, 10);
fill(a, 10); // Try to add duplicates
fill(a, 10);
a.addAll(fill(new TreeSet(), 10));
System.out.println(a);
}
public static void main(String[] args) {
test(new HashSet());
test(new TreeSet());
test(new LinkedHashSet());
monitor.expect(new String[] {
"[2 , 4 , 9 , 8 , 6 , 1 , 3 , 7 , 5 , 0 ]",
"[9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ]",
"[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]"
});
}
} ///:~该例子把MyType 这种类型的元素放入set中,mytype是书中前面定义的,只是实现了comparable接口的compareTo()方法, 没有定义equals().
这是不是说equals()方法可以用comparable接口的compareTo()方法来代替?
由于set自己有一套内置的排序机制,
所以如果要将自己创建的类加入set集合,必须实现Comparable接口.
HashSet比较的是hash值。需要复写对象的hash算法。TreeSet是使用compare建立树,要求对象实现Comparable接口。