Jason5563 发表于 2013-2-3 11:25:38

Java Set 总结

总结一下 Set 在使用时需要的注意事项:
 
Set (interface): 为了实现唯一性,需要实现 equals 方法
 
HashSet : 实现 hashCode 方法
TreeSet: 实现 Comparable 接口,实现compareTo方法
LinkedHashSet: 实现 hashCode方法
 
结果:







SetType cannot be cast to java.lang.Comparable
HashType cannot be cast to java.lang.Comparable
分析:
前三行,唯一
中四行,失败,不唯一。 原因是 hashCode
后两行, 失败,异常。原因,未实现 Comparable 接口
 
 
import java.lang.reflect.InvocationTargetException;import java.util.*;// 简单对象 实现 equalsclass SetType {int i;public SetType(int n) {i=n;}public boolean equals( Object o ){if(o!=null && o instanceof SetType){return i==((SetType)o).i;}return false;}public String toString(){return Integer.toString(i);}}// Hash 对象 ,实现了 hashCodeclass HashType extends SetType{public HashType(int n){super(n);}public int hashCode(){return i;}}// Tree对象,实现 compareTo 对象class TreeType extends SetType implements Comparable<TreeType>{public TreeType(int n){ super(n);}@Overridepublic int compareTo(TreeType o) {return i>o.i?-1:( i==o.i?0:1 );}}public class TypeForSets{// 填充static<T>Set<T> fill (Set<T> set, Class<T> type) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{for(int i=0;i<10;i++)set.add( type.getConstructor(int.class).newInstance(i) );return set;}// 测试static <T> void test(Set<T> set, Class<T> type) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{fill(set,type);fill(set,type);fill(set,type);System.out.println(set);}public static void main(String [] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{// 这些事符合规范的Set使用    test(new HashSet<HashType>(), HashType.class);    test(new LinkedHashSet<HashType>(), HashType.class);    test(new TreeSet<TreeType>(), TreeType.class); // Things that don't work:    // SetType,TreeType对象 未实现hashCode    test(new HashSet<SetType>(), SetType.class);    test(new HashSet<TreeType>(), TreeType.class);    test(new LinkedHashSet<SetType>(), SetType.class);    test(new LinkedHashSet<TreeType>(), TreeType.class);      // SetType,HashType 未实现 Comparable 接口    try {      test(new TreeSet<SetType>(), SetType.class);    } catch(Exception e) {      System.out.println(e.getMessage());    }    try {      test(new TreeSet<HashType>(), HashType.class);    } catch(Exception e) {      System.out.println(e.getMessage());    }}} 
页: [1]
查看完整版本: Java Set 总结