Actuation when using generics in Java

I wrote my own Stack class (for the corresponding code, see below). In the next() method, I am forced to use current.item in Item , but I do not know why. The type current.item should already be Item , and therefore casting should not be necessary, but if I do not produce it, I get an error.

 public class Stack<Item> implements Iterable<Item> { private class Node { Item item; Node next; } private Node first= null; public Iterator<Item> iterator() { return new StackIterator(); } private class StackIterator<Item> implements Iterator<Item> { private Node current = first; public Item next(){ Item item = (Item)current.item; current = current.next; return item; } } } 
+5
source share
4 answers

The type parameter of StackIterator<Item> hides the type of Item , which is entered in the definition of the Stack<Item> class.

This is why you need to throw (or add the @SuppressWarnings("hiding") annotation).

To get rid of the warning, simply remove the duplicate type:

 private class StackIterator implements Iterator<Item> { } 
+7
source

You used <Item> as a type parameter for Stack and StackIterator , whereas what you really want to do is StackIterator without a parameter and just indicate that it implements Iterator<Item> :

  private class StackIterator implements Iterator<Item> { private Node current = first; @Override public Item next() { Item item = current.item; // no need to cast now current = current.next; return item; } } 
+7
source

Your StackIterator class is an inner Stack class. This especially means that it is not static. Therefore, he already knows about the parameter of type Item .

You make a mistake when StackIterator has its own parameter of type Item . This obscures the type parameter of the outer class.

So, just remove the type parameter from StackIterator :

 public class Stack<Item> implements Iterable<Item> { private class Node { Item item; Node next; } private Node first = null; @Override public Iterator<Item> iterator() { return new StackIterator(); } private class StackIterator implements Iterator<Item> { private Node current = Stack.this.first; @Override public Item next() { Item item = this.current.item; this.current = this.current.next; return item; } } } 
+3
source

If you want the <Item> in the StackIterator be of the same type as the enclosing <Item> associated with the Stack , remove the <Item> StackIterator in the StackIterator .

If you want the <Item> in StackIterator different from the <Item> associated with Stack , but you want to have access to the properties of the parent Stack , rename <Item> to something else.

+1
source

Source: https://habr.com/ru/post/1204801/


All Articles