LinkedList implementation in Java with generics and improved for

I need you to look at my Single Linked List (SLL) implementation, please. An implementation should use generics and be able to use advanced ones for.

The problem is that when I execute for (Number n : list) list a MyLinkedList<Integer> or MyLinkedList<Double> , I get the error: "Mismatch type: cannot be converted from element type to Object to Number".

This is what I have. Parts that I'm not very sure about are generics and iterators.

Thanks in advance.

 import java.util.Iterator; public class MyLinkedList<T> implements Iterable<Object> { private Node head; public MyLinkedList () { head = null; } public void add (Node n) { if (head == null) { head = n; } else { Node node = head; while (node.next != null) { node = node.next; } node = n; } } public Iterator iterator() { return new MyLinkedListIterator (head); } public int size () { int ret = 0; MyLinkedListIterator it = new MyLinkedListIterator (head); while (it.hasNext ()) { it.next(); ret++; } return ret; } public Node getHead () { return head; } } class MyLinkedListIterator<T> implements Iterator { private Node node; public MyLinkedListIterator (Node h) { node = h; } public MyLinkedListIterator (MyLinkedList<T> l) { this(l.getHead ()); } public boolean hasNext () { if (node.next == null) { return false; } else { return true; } } public Object next () { return node.next; } public void remove () { } } 
+4
source share
5 answers
  • You should have Iterable<T> instead of Iterable<Object> .
  • add(Node) does not actually add the object to the list.
  • MyLinkedListIterator<T> must implement Iterator<T> .
  • MyLinkedListIterator.hasNext() throw a NullPointerException if the list is empty.
  • MyLinkedListIterator.next() does not go to the next item in the list.
+8
source

You must return an Iterator<T> from the iterator method, and you must also extend Iterable<T> instead of Iterable<Object> .

In addition, your MyLinkedListIterator<T> should implement Iterator<T> . Then it should work.

+2
source

Why aren't you using <E>

 public class Node<E>{ E data; Node<E> next; } public class SinglyLinkedList<E> { Node<E> start; int size; ....... } 

Look here for a comprehensive implementation.

+1
source

In addition to what others have said, you should probably not be exposed to Node in your public methods - nodes should be a purely internal aspect of the implementation.

+1
source

Expanding point: MyLinkedListIterator.next () does not go to the next item in the list.

the following method should be something like these lines in order to make it work:

 public T next() { if(isFirstNode) { isFirstNode = false; return node.data; } node = node.next; return node.data; } 
0
source

All Articles