0

这是我的课:

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”?

谢谢,//克里斯

4

1 回答 1

1

改用这个:

MultiSet<?> o = (MultiSet<?>) object;

由于泛型在 java 中的实现方式,这是必要的。

于 2011-12-09T19:40:19.083 回答