Reputation: 9
When i use anonymous inner classes to create Nodes. When i print all the keys, they are printing as 0's, instead of the values i assigned in the anonymous class declaration. Am i doing something wrong? Here's my code:
public class LinkedListTest {
Node head;
public void addInOrder(final int value) {
if (head == null) {
head = new Node() {
int key = value;
};
}
else if(head.key > value) {
final Node temp = head;
head = new Node() {
int key = value;
Node next = temp;
};
}
else {
Node theNode = head;
while(theNode.key < value) {
if (theNode.next == null) {
theNode.next = new Node() {
int key = value;
};
return;
}
else if(theNode.next.key > value) {
final Node temp = theNode.next;
theNode.next = new Node() {
int key = value;
Node next = temp;
};
return;
}
theNode = theNode.next;
}
}
}
And this is my class declaration for my Node:
class Node {
int key;
Node next;
}
And this is my printing method:
public void printAll(Node hasNode) {
if (hasNode != null) {
System.out.println(hasNode.key);
if (hasNode.next != null) {
printAll(hasNode.next);
}
}
}
Upvotes: 0
Views: 60
Reputation: 122518
As Andy Turner answered, you declared key
and next
in your anonymous class as instance variables of the anonymous class, and you are initializing those instance variables, but they are unrelated to the instance variables of the same name from the class Node
.
If it would make it easier to understand, this:
theNode.next = new Node() {
int key = value;
Node next = temp;
};
is equivalent to a local class like this:
class Foo extends Node {
int key = value;
Node next = temp;
};
theNode.next = new Foo();
or you can even lift the class out of the method so the capturing is more clear:
// outside the method
class Foo extends Node {
int key;
Node next;
Foo(int value, Node temp) { key = value; next = temp; }
};
// inside the method
theNode.next = new Foo(value, temp);
The point is, in all of these cases, you are assigning values to the instance variables of Foo
, and not the instance variables of Node
.
It is possible for you to perform initialization in the anonymous class that allows you to assign to the instance variables of Node
. Although anonymous classes don't have constructors (they don't need them), initialization can be done in the instance initializer:
theNode.next = new Node() {
{
key = value;
next = temp;
}
};
It's often written in the "double brace initialization" style:
theNode.next = new Node() {{
key = value;
next = temp;
}};
Upvotes: 0
Reputation: 140534
This is because you aren't assigning values to the fields in Node
, you are assigning values to the fields in the anonymous subclass with the same names.
Add a constructor to Node
, and don't create an anonymous subclass:
class Node {
int key;
Node next;
Node(int key, Node next) {
this.key = key; this.next = next;
}
}
Optionally, you can add a second constructor which just takes the key:
Node(int key) {
this(key, null);
}
The alternative is just calling new Node(key, null)
.
Upvotes: 3