这是我的课:
public class MultiSet<E> extends AbstractCollection<E>
{
private int size = 0;
private Map<E, Integer> values = new HashMap<E, Integer>();
public MultiSet()
{
}
public MultiSet(Collection<E> c)
{
addAll(c);
}
@Override
public boolean add(E o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
public Iterator<E> iterator()
{
return new Iterator<E>()
{
private Iterator<E> iterator = values.keySet().iterator();
private int remaining = 0;
private E current = null;
public boolean hasNext()
{
return remaining > 0 || iterator.hasNext();
}
public E next()
{
if (remaining == 0)
{
remaining = values.get(current);
}
remaining--;
return current;
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
public boolean equals(Object object)
{
if (this == object) return true;
if (this == null) return false;
if (this.getClass() != object.getClass()) return false;
MultiSet<E> o = (MultiSet<E>) object;
return o.values.equals(values);
}
public int hashCode()
{
return values.hashCode()*163 + new Integer(size).hashCode()*389;
}
public String toString()
{
String res = "";
for (E e : values.keySet());
//res = ???;
return getClass().getName() + res;
}
public int size()
{
return size;
}
}
所以基本上,我需要正确实现我的添加/删除方法,以向 Set
添加或删除元素。 .
对我来说,这似乎是我的 equals
是正确的,但 Eclipse 在该行中表示:
MultiSet<E> o = (MultiSet<E>) object;
有一个unchecked cast from object to Multiset<E>
有什么想法吗?
另外,在我的 toString
中方法,我不是 100% 确定如何定义“res”?
谢谢, //克里斯
最佳答案
改用这个:
MultiSet<?> o = (MultiSet<?>) object;
由于泛型在 java 中的实现方式,这是必要的。
关于java - MultiSet 类中添加/删除/等于/字符串方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450518/