java中一个程序typesforsets

来源:百度知道 编辑:UC知道 时间:2024/06/09 12:44:32
import java.util.*;

class SetType {
int i;
public SetType(int n) { i = n; }
public boolean equals(Object o) {
return o instanceof SetType && (i == ((SetType)o).i);
}
public String toString() { return Integer.toString(i); }
}

class HashType extends SetType {
public HashType(int n) { super(n); }
public int hashCode() { return i; }
}

class TreeType extends SetType
implements Comparable<TreeType> {
public TreeType(int n) { super(n); }
public int compareTo(TreeType arg) {
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
}

public class TypesForSets {
static <T> Set<T> fill(Set<T> set, Class<T> type) {
try {
for(int i = 0; i < 10; i++)
set.add(
type.getConstructor(int.class).newInstance(i));
} catch(Exception e) {
throw new Runti

是谁给你出的这个题,那么坏。你在main方法中用的都是HashSet或者HashSet得子类LinkedHashSet,这2个类是根据hashCode来判断元素是否重复的,你在SetType类中加入public int hashCode() { return i; }方法,结果就不会重复了。

TreeSet才是用compareTo来比较元素是否重复的,但是你这里都没有TreeSet,即使你TreeType实现了compareTo方法,对于HashSet和LinkedHashSet来说是没用的。

HashType这个类虽然重写了hashCode方法,但是你却没用到过。所以看不到结果。

另外再补充一个知识点给你,如果要用equals来比较元素是否重复,要用CopyOnWriteArraySet。