0

I came across a code snippet as below, for implementing a linked list:

public static class Element<AnyType> {
    private AnyType data; 
    private Element<AnyType> next; // reference to the next node
    Element(AnyType d, Element<AnyType> e) {
        data = d;
        next = e;
    }
}

Can someone tell me how this is possible? How can a Java class (in my case Element) have an instance variable of its own type?

emecas
  • 1,586
  • 3
  • 27
  • 43
GHSH
  • 9
  • 3
  • I'm not sure I understand what's throwing you off. Why do you think it *shouldn't* be able to happen? – Silvio Mayolo Apr 01 '18 at 01:06
  • Here `AnyType` is a generic type; and it's quite possible for a class to contain a reference to an instance of its' own type. – Elliott Frisch Apr 01 '18 at 01:07
  • 3
    This isn't C++; `Element` having an instance variable `Element next` doesn't mean that the memory layout of an `Element` has to physically encompass the memory layout of another `Element` ad infinitum. – user2357112 Apr 01 '18 at 01:09

1 Answers1

1

How can a Java class (in my case Element) have an instance variable of its own type?

Actually it doesn't. Java only has primitive and reference variables, not instances. This means next is a just a reference which is initially null.

private AnyType data; // a reference to an AnyType object
private Element<AnyType> next; // reference to the next node

BTW The comment does state it's a reference not an instance.

Why is there no special symbol like in C++? because in Java there is no other option so no reason to have a & or similar.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130