0
Node( T itemArg, Node<T>  nextArg ) {

    this.item = itemArg;       
    this.next = nextArg;

}

Is this the right way to represent generic constructor

4
  • 1
    It would depends on what you are trying to do... but in principle, this is not incorrect. Commented May 2, 2018 at 5:57
  • Possible duplicate of how to create a generic constructor for a generic class in java? You are correct that that would work. Commented May 2, 2018 at 5:58
  • General comment: This 'construct' resembles the old C-way of representing linked lists. In Java, we have many high-level data structures (including linked and double-linked lists), so this way of representing a linked list is not necessary. Commented May 2, 2018 at 6:16
  • The only slightly unusual thing here is unrelated to the generics: there is no need to call the parameter fooArg and qualify the field this.foo: foo = fooArg;, or renaming the parameter to foo and using this.foo = foo;, is more usual. But it isn't wrong to do it like this. Commented May 2, 2018 at 6:24

1 Answer 1

1

This is correct, as long as the parameter is specified in the class definition.

EDIT: Ensure item is an instance of T, and next is an instance of Node<T>.

public class Node<T> {
  T item;
  Node<T> next;
  //your constructor
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you go there, you should also specifiy that item should be an instance of T and next an instance of Node<T>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.