使用泛型并试图摆脱不安全的操作警告

时间:2015-02-20 22:28:53

标签: java generics compiler-warnings

这是我的代码,但我不断收到“注意:LinkedListAdd.java使用未经检查或不安全的操作。”我正试图尽我所能摆脱它,但似乎没有任何工作。基类编译很好,没有警告,检查似乎来自add all方法。有什么想法吗?

public class LinkedListAdd<E extends Comparable <E> > extends LinkedList<E>
{
  public LinkedListAdd()
  {
     super();
  }

  public <E extends Comparable<E> > boolean addAll(final int index, final E[] array)
  {
     if(index < 0 || index > this.size())
        throw new IndexOutOfBoundsException("Index out of bounds");
     if(array == null)
        throw new NullPointerException("Null array");

     Node nn = null; 
     for(int y = array.length - 1; y >= 0; y--)
     {
        nn = new Node(array[y], null);
        if(this.size() == 0)
        {
           this.head.next = nn;
           this.size += 1;
        }
        else
        {
           Node cur = this.head.next, prev = null;
           for(int x = 0; x < index; x++)
           {
              prev = cur;
              cur = cur.next;
           }
           if(prev == null)
           {
              nn.next = cur;
              this.head.next = nn;
              this.size += 1;
           }
           else
           {
              prev.next = nn;
              nn.next = cur;
              this.size += 1;
           }
        }
     }
     if(nn == null)
        return false;
     return true;
  }

}//end class LinkedListSort

这是基类

  public class LinkedList<E extends Comparable <E> >
  {
     protected static class Node<E extends Comparable <E> >
     {
        public E data;
        public Node<E> next;

        public Node()
        {
           this.next = null;
           this.data = null;
        }// end DVC

        public Node(final E data, final Node<E> next)
        {
           this.next = next;
           this.data = data;
        }// end EVC
     }// end class Node

     protected Node <E> head;
     protected int size;

     public LinkedList()
     {
        this.head = new Node<>();
        this.size = 0;
     }

     public void clear()
     {
        this.head = null;
        this.size = 0;
     }// end clear

     public int size(){return this.size;}

     public void addFirst(final E data)
     {
        this.head.next = new Node<>(data, this.head.next);
        size ++;
     }// end

     public String toString()
     {
        String temp = "List size: " + this.size;
        if(this.head.next == null)
           return temp += "\nEmpty List";

        else
        {
           temp += "\n";
           Node<E> cur = head.next;
           while(cur != null)
           {
              temp += cur.data + " ";
              cur = cur.next;
           }
           return temp;
        }// end else

     }// end toString

  }// end class

1 个答案:

答案 0 :(得分:2)

我建议做的一些事情;首先,我在你的头/下一个/大小/数据上添加get / set方法并将这些字段设为私有

关于你的仿制品;

方法签名应该是

public boolean addAll(final int index, final E[] array)

并且您对该方法中节点的声明需要

Node<E> node