【问题标题】:Duplicate field error while converting a class to generic in Java在 Java 中将类转换为泛型时出现重复字段错误
【发布时间】:2020-12-27 14:36:02
【问题描述】:

我写了一个代码来在java中实现链表,但是当我把它转换成一个泛型类时,我得到了一堆错误。

public class LinkedList<E> {
static class Node<E> {
    E data;             //encountering error here - "Duplicate field LinkedList.Node<E>.data"
    Node<E> next;

 public Node<E>(E data){   // error - Syntax error on token ">", Identifier expected after this token
         this.data = data;
         next = null;
    }
 } 

 Node<E> head;
 void add(E data){
    Node<E> toAdd = new Node<E>(data);   //error - The constructor LinkedList.Node<E>(E) is undefined
    if(head == null){
        head = toAdd;
        return;
    }
    Node<E> temp = head;
    while(temp.next != null){
        temp = temp.next;
    }
    temp.next = toAdd; 
 }

  void print(){
    Node<E> temp = head;
    while(temp != null)
    {
        System.out.print(temp.data + " ");
        temp = temp.next;
    }
  }
  boolean isEmpty(){
    return head == null;
 }

}

当我没有将类设为通用时,代码运行良好

【问题讨论】:

    标签: java generics linked-list generic-programming


    【解决方案1】:

    您没有在构造函数中包含泛型。只是:

    public Node(E data) { ... }
    

    static class Node&lt;E&gt; {} 中的 E 声明了变量。就像int foo; 中的foo。所有其他地方(好吧,除了public class LinkedList&lt;E&gt;,它声明了一个完全不同的类型变量,名称完全相同——但你的 Node 类是静态的,所以在这里没关系)正在使用它。您无需重复声明 E 不止一次。您也无需在每次使用时都重新声明int foo;:您只需执行一次。

    【讨论】:

      【解决方案2】:
      public class LinkedList<E> {
          Node<E> head;
      
          void add(E data) {
              Node<E> toAdd = new Node<E>(data);
              if (head == null) {
                  head = toAdd;
                  return;
              }
              Node<E> temp = head;
              while (temp.next != null) {
                  temp = temp.next;
              }
              temp.next = toAdd;
          }
      
          void print() {
              Node<E> temp = head;
              while (temp != null) {
                  System.out.print(temp.data + " ");
                  temp = temp.next;
              }
          }
      
          boolean isEmpty() {
              return head == null;
          }
      
          public static class Node<E> {
              E data;
              Node<E> next;
      
              public Node(E data) {
                  this.data = data;
                  next = null;
              }
          }
      
      }
      

      试试这个。构造函数没有得到类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 2021-05-16
        • 2012-02-07
        • 1970-01-01
        • 2012-12-14
        相关资源
        最近更新 更多