2

私は自分自身をよりよく理解するために、反復子を使用してカスタムリストを実装したいと考えていますが、初めて自分で使用しているジェネリック型の問題に遭遇しました。これは私のクラスの重要な部分です

public class MyList<T> implements Iterable<T> 
{

// Unrelated code

@Override
public Iterator<T> iterator()
{
    return new Iterator<T>()
    {
        private Node position = firstNode;

        public boolean hasNext()
        {
            return position.getNext() != null;
        }

        public T next()
        {
            String current = "";
            if (this.hasNext())
            {
                current = position.getData();
                position = position.getNext();
            }
            return (T) current;

ここで Eclipse は、これはチェックされていないキャストであると言っているので、次のように変更してみました。

            return (T) (current instanceof T?current:null);

しかし、Eclipse は次のエラーを出します。

@SupressWarnings を使用せずに警告を取り除くにはどうすればよいですか?

        }

        public void remove()
        {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };
}

    //unrelated code
}
4

2 に答える 2

3

You can get rid of all of the casting and instanceof by generifying Node.

Something like:

class Node<T> {
  private Node<T> next;
  private T data;

  public Node<T> getNext () {
    return next;
  }

  public T getData () {
    return data;
  }
}
于 2013-10-10T09:57:59.137 に答える