2014-10-13 2 views
1

Я думаю, что я настроил свой класс правильно, чтобы быть общим, но когда я пытаюсь вызвать методы, которые, похоже, не корректно настраивают мои другие методы. Я предположил, что мои переменные являются общими? или я передаю свои методы переменным?Как реализовать Java Generics

public class LinkedList<E> 
{ 
    // reference to the head node. 
    private E head; 
    private int listCount; 


    public boolean delete(E string) 
    // post: removes the element at the specified position in this list. 
    {  
     Node current = head.getNext(); 

     while(true){ 
      if(current == null){ 
       return false; 
      }else if(current.getNext().getData().equals(string)){ 
       if(current.getNext() == null){ 
        current.setNext(null); 
       }else{ 
        current.setNext(current.getNext().getNext()); 
       } 
       listCount--; // decrement the number of elements variable 
       return true; 
      }else{ 
       current = current.getNext(); 
      } 
     } 
    } 

    private class Node<E extends Comparable<E>> 
    { 
     // reference to the next node in the chain, 
     E next; 
     // data carried by this node. 
     // could be of any type you need. 
     E data; 


     // Node constructor 
     public Node(E _data) 
     { 
      next = null; 
      data = _data; 
     } 

     // another Node constructor if we want to 
     // specify the node to point to. 
     public Node(E _data, E _next) 
     { 
      next = _next; 
      data = _data; 
     } 

     // these methods should be self-explanatory 
     public E getData() 
     { 
      return data; 
     } 

     public void setData(E _data) 
     { 
      data = _data; 
     } 

     public E getNext() 
     { 
      return next; 
     } 

     public void setNext(E _next) 
     { 
      next = _next; 
     } 
    } 


} 
+1

Что именно проблема? – aioobe

+2

Не должно 'head' и' next' быть типа 'Node ' вместо 'E'? – JonK

+0

Ваш код выглядит нормально (хотя @JonK выше меня абсолютно прав), не могли бы вы изменить свой вопрос, чтобы включить пример того, что вы хотите сделать, но не удается? – MrHug

ответ

3

Типы ваших переменных были немного испорчены.

  • Node.next должен быть Node
  • LinkedList.head должен быть Node
  • Node не должны быть общими. (Параметр E типа находится в области видимости для внутреннего класса.)

Вот версия, которая составляет:

class LinkedList<E> { 
    // reference to the head node. 
    private Node head; 
    private int listCount; 

    public boolean delete(E string) 
    // post: removes the element at the specified position in this list. 
    { 
     Node current = head; 

     while (true) { 
      if (current == null) { 
       return false; 
      } else if (current.getData().equals(string)) { 
       if (current.getNext() == null) { 
        current.setNext(null); 
       } else { 
        current.setNext(current.getNext().getNext()); 
       } 
       listCount--; // decrement the number of elements variable 
       return true; 
      } else { 
       current = current.getNext(); 
      } 
     } 
    } 

    private class Node { 
     // reference to the next node in the chain, 
     Node next; 
     // data carried by this node. 
     // could be of any type you need. 
     E data; 

     // Node constructor 
     public Node(E _data) { 
      next = null; 
      data = _data; 
     } 

     // another Node constructor if we want to 
     // specify the node to point to. 
     public Node(E _data, Node _next) { 
      next = _next; 
      data = _data; 
     } 

     // these methods should be self-explanatory 
     public E getData() { 
      return data; 
     } 

     public void setData(E _data) { 
      data = _data; 
     } 

     public Node getNext() { 
      return next; 
     } 

     public void setNext(Node _next) { 
      next = _next; 
     } 
    } 

} 

Глядя на ваш метод delete, я думаю, что это немного глючит, хотя. Когда вы дойдете до узла, где data равен string, вы измените следующий указатель на то, что узел, в то время как вы должны изменить следующий указатель previous узел.

Я хотел бы попробовать что-то вроде этого:

Node current = head, prev = null; 
    while (current != null) { 
     if (current.getData().equals(string)) { 
      // Remove current from list 
      if (current == head) { 
       head = current.getNext(); 
      } else { 
       prev.setNext(current.getNext()); 
      } 

      listCount--; // decrement the number of elements variable 
      return true; 
     } 
     prev = current; 
     current = current.getNext(); 
    } 
+0

Спасибо. Мне удалось собрать все. Однако у меня есть еще один вопрос. Я должен иметь класс Node как частный класс Node > Я устал, имея LInkedList как открытый класс LinkedList >, но это только что оставило меня с этим предупреждением от затмения «LinkedList.Node - это необработанный тип. к родовому типу LinkedList .Node следует параметризовать « – Nevets0423

+0

Хмм. Интересно. Я не могу точно сказать, из-за этого. Отправьте еще один вопрос, и мы увидим, знает ли кто-нибудь еще ... – aioobe