1

I am doing lab, I viewed a lot of Java Generics example, but I cannot understand it. My goal is achieving Linked Stack. It have 2 files: IntStack.java and IntNode.java. The part of these code is:

public class IntNode { private int element = 0; private IntNode next = null; public IntNode(final int data, final IntNode next) { this.element = data; this.next = next; } public class IntStack { private IntNode top = null; public boolean isEmpty() { return this.top == null; } 

How to convert them to generics type? I know it should use <T>,and I write these code, it is correct or not?

public class Node<T> { private T element; private Node<T> next = null; public Node(final T data,final Node next) { this.element = data; this.next = next; } } 
2
  • 2
    Node next shouldn't use raw type, thus should be parametrized with T: Node<T> next . Commented Nov 28, 2018 at 7:54
  • @LuCio Thank you very much! Commented Nov 28, 2018 at 8:33

1 Answer 1

1

You are close. The Node parameter of the Node constructor should also be parameterized:

public class Node<T> { private T element; private Node<T> next = null; public Node(final T data,final Node<T> next) { this.element = data; this.next = next; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.