要求实现接口java.util.Set,元素和hash code无关
和HashSet不同的是要求此Set和元素hash code无关,只和equals相关。
要支持null元素。

解决方案 »

  1.   

    CSDN 的脸上就是写着题目一出,就得给代码!
      

  2.   

    要求不是很明确。
      Set集合本来就允许null元素, 还有如果只是要求与 hashcode 无关, 可以用treeSet,
      或者用hashSet ,重写hashCode 方法,使之返回值与 equals 相关。
      

  3.   

    HashSet和hash code有关;
    TreeSet的话,元素又多余实现了SortedSet。
      

  4.   

    这个其实和Set都没有什么关系了。equals只可以返回true和false,所以根本无法算出hashCode。
    public class MySet<E> implements Set<E> {
    List<E> list = new ArrayList<E>(); public boolean add(E o) {
    if(list.contains(o))
    return false;
    list.add(o);
    return true;
    } public boolean addAll(Collection<? extends E> c) {
    boolean result = false;
    for(E o : c)
    result |= add(o);
    return result;
    } public void clear() {
    list.clear();
    } public boolean contains(Object o) {
    return list.contains(o);
    } public boolean containsAll(Collection<?> c) {
    for(Object o : c)
    if(!contains(o))
    return false;
    return true;
    } public boolean isEmpty() {
    return list.isEmpty();
    } public Iterator<E> iterator() {
    return list.iterator();
    } public boolean remove(Object o) {
    return list.remove(o);
    } public boolean removeAll(Collection<?> c) {
    return list.removeAll(c);
    } public boolean retainAll(Collection<?> c) {
    return list.retainAll(c);
    } public int size() {
    return list.size();
    } public Object[] toArray() {
    return list.toArray();
    } public <T> T[] toArray(T[] a) {
    return list.toArray(a);
    }
    }
    因为在调用add(newitem)时,你除了逐一比较已经存在于set中的对象外,你根本无法迅速判断这个newitem是否可能与set中现有对象是否相同。所以只能逐一比较。