how can i make field node stop evaluating as Null? - java

How do I make the node "ahead" for the parameter "head" of the object stop equaling "Null" when I use .getNext() on it? I just get NullPointerException everytime
LinkedNode have parameters LinkedNode and E data.
package sets;
import java.util.Iterator;
import java.util.NoSuchElementException;
class LinkedNodeIterator<E> implements Iterator<E> {
private LinkedNode<E> ahead;
private E data;
public LinkedNodeIterator(LinkedNode<E> head) {
ahead = head;
data = ahead.getData();
}
public boolean hasNext(){
boolean here = false;
LinkedNode<E> currNode = this.ahead;
if(currNode.getNext() != null) here = true;
return (here);
}
//othercode...
}
and
package sets;
public class LinkedNode<E> {
private E data;
private LinkedNode<E> next;
public LinkedNode(E data, LinkedNode<E> next) {
this.data = data;
this.next = next;
}
public E getData(){
return data;
}
public LinkedNode<E> getNext(){
return this.next;
}
}

Given this program, and assuming there are no more methods which modify the ahead variable, the only possible way for the ahead to be null, is in its initialization: In other words, ahead is null only when parameter head is null.
I suggest you two things:
Make sure there are no more methods modifying the ahead variable. One sure way to achieve this is declaring it as final (and also a good practice, too).
Add an assert in the first line of the constructor:
assert head!=null;
... and run your program with "java -ea" to enable assertions.

Related

required type T, Provided Object

I try to implement Generic linked list but I get an error:
required type T, Provided Object in the line T val = head.val;
DDLinkedList class:
public class DDLinkedList <T>{
private ListElement head;
private ListElement tail;
protected <T> void addToHead(T val){
if (this.isEmpty()){
head = new ListElement(val,head);
tail = head;
}else {
head = new ListElement(val, head);
head.next.prev = head;
}
}
protected <T> T removeFromHead(){
if(this.isEmpty()){
return null;
}
T val = head.val;
head = head.next;
return val;
}
}
the List Element class:
public static class ListElement<T> {
private ListElement next;
private ListElement prev;
private T val;
public ListElement(){
this(null, null, null);
}
public ListElement(T val){
this(val, null, null);
}
public ListElement(T val, ListElement next, ListElement prev){
this.val = val;
this.next = next;
this.prev = prev;
}
}
What can be the problem?
Let's have a look at your code (and the changes I suggest regarding Generics):
public class DDLinkedList<T> {
private ListElement<T> head;
private ListElement<T> tail;
Here, you want head and tail to be specific ListElements containing a T value, not just any raw ListElement. That's what ListElement<T> expresses.
protected void addToHead(T val){
Don't use protected <T> void addToHead(T val){, as the <T> introduces a new variable type, incidentally also called T, but unrelated to the intended list element type T.
if (this.isEmpty()){
head = new ListElement<T>(val, head, null);
You'll want to declare that you create a ListElement of element type T. (Your version surely gives warnings on using raw types.) And there's no two-argument constructor for ListElement.
tail = head;
}else {
head = new ListElement<T>(val, head, null);
head.next.prev = head;
}
}
protected T removeFromHead(){
if(this.isEmpty()){
return null;
}
T val = head.val;
As a result of declaring private ListElement<T> head;, the compiler now knows that head.val is of type T
head = head.next;
return val;
}
}
public static class ListElement<T> {
private ListElement<T> next;
private ListElement<T> prev;
In a list with element type T, the next and prev ListElements will surely also contain T.
private T val;
public ListElement(){
this(null, null, null);
}
public ListElement(T val){
this(val, null, null);
}
public ListElement(T val, ListElement<T> next, ListElement<T> prev){
this.val = val;
this.next = next;
this.prev = prev;
}
}
Then, there is the issue that you have private fields in ListElement, but access them from outside. A solution is to keep the fields private, to introduce getters and setters for the fields, and to use the getters and setters instead of the direct field access. Or even better, move the linking logic into the ListElement class, so you don't need the setters at all.
The error is caused because you have redeclared the type T in removeFromHead(); T is already declared in the class declaration so the compiler is trying to equate two different types of the same name.
Redeclare the method to: protected T removeFromHead() and that error should go away. (And you also have the same issue in the other class method.)
As the commenters have noted, you have also missed the type parameter T off all occurrences of ListElement within the declaration of ListElement, which generates separate warnings.
Change the following lines
private ListElement<T> head;
private ListElement<T> tail;

setting a field in a class, does the original object not change the field?

I am trying to figure out how this works under the hood. I have a feeling i am overlooking this but I have this code.
newNode.setNextNode(root);
root = newNode;
return true;
code for node class
public class Node <T extends Comparable <T>> implements Comparable<T>{
private Node nextNode = null;
private T data;
public Node(T data){
this.data = data;
}
public boolean setNextNode(Node nextNode){
this.nextNode = nextNode;
return true;
}
public Node next(){
return nextNode;
}
public T getData(){
return data;
}
#Override
public String toString() {
return data.toString();
}
#Override
public int compareTo(T o) {
return getData().compareTo((T) nextNode.getData());
}
}
root is now set to a field in my new node.
when then do root = newNode. why when i do root.next does it not just give me back the root?
when I do the setter does it create a complete copy of the object? as I am aware when you make one object equal to another the reference refers to the same object. therefore it can change the original object.
if anyone could explain this would be great
Thank you

Why using a class as a variable member inside that said class

I am new to Java and been studying it. So I am having trouble to understand what are these and how it being processed by Java also why are we declaring these variables like that. I mean can you educate me on this?
Public abstract class ListItem {
protected Listitem leftLink = null;
protected Listitem rightLink = null;
protected Object value;
some code here
}
Thanks in advance!
Why declare a Class field which has the ClassName as variable type instead of a int, string... ?
Because the developer needs to. Sometimes, an instance of a class must reference another instance of the same class. A typical example is the LinkedList.
Consider a linked list as a sequence of nodes. Each node knows the next one to be linked. Here would be a naive implementation of a node:
class Node<T> {
private Node<T> next;
private T value;
Node(T value) {
this.value = value;
}
public T getValue() {
return value;
}
void setNext(Node<T> next) {
this.next = next;
}
}
As you can see, the class Node contains a variable member of type Node, to reference the next element of the linked list. Finally, a simplistic implementation of the linked list would be:
class LinkedList<T> {
private Node<T> first;
private Node<T> last;
private int length = 0;
public void add(T value) {
Node<T> node = new Node<T>(value);
if(length != 0) {
last.setNext(node);
last = node;
}
else {
first = node;
last = node;
}
length++;
}
public Node<T> getFirst() {
return first;
}
}
When a new node is added to the collection, the previous last node references it and therefore, becomes the new last node.

Getting NullPointer implementing a LinkedSet [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a LinkedSet object class that implements a modified Set interface. I am getting a NullPointerException when I try and check if the firstNode is pointing to null or not. I'm not really sure how to solve this issue.
Here is relevant code.
Constructor for overall Set object
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
Method that is holding me up
public int getSize() {
int size = 1;
Node current = firstNode;
while ((current.next) != null) {
size++;
current = current.next;
}
return size;
} // end getSize()
isEmpty() method
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
Here is private inner class for Node objects
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
And lastly here is the main tester method.
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.getSize()); //Get error here
}
}
Your set is empty if it has no nodes. Therefore your isEmpty() implementation is your problem, since it assumes you always have a firstNode even though you explicitly set it to null in the constructor.
Try this:
public boolean isEmpty() {
return firstNode == null;
}
Edit after the first problem was edited away:
You still access null (which causes the NullPointerException) since you set current to firstNode which in turn has never been set to anything but null.
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
This line gives you NullPointerException, I hope:
Node next = firstNode.next; //Get error here
Because firstNode is probably null and not pointing anywhere so far. It's also best practice to handle NullPointerException. So, what you should do is:
public boolean isEmpty() {
if (firstNode == null) { return true;}
return false;
} // end isEmpty()
Also, do not check null as:
next.equals(null)
Always check it as:
null == next or next == null
You need to check if firstNode is null before you try to access it in the line with the error, since you initialize it with null.
In
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
firstNode is null and you are not initializing the memory to the node and accessing it afterwards.That's the reason you are getting null pointer exception because you are accessing null. Change it to.
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = new Node();
} // end Constructor
To check if empty
public boolean isEmpty() {
return firstNode==null;
} // end isEmpty()
Node Class
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
next= new Node();
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
Main
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.isEmpty());
}
}

Generics collection implementation java compilation error

EDIT :
public class LinkedList<E> {
private class Node {
protected Node next, prev;
protected E data;
protected Node(E dat) {
data = dat;
next = prev = null;
}
}
private Node head, tail;
public LinkedList() {
(head = new Node(null)).next = tail = new Node(null);
tail.prev = head;
tail.next = head.prev = null;
}
public class LinkedListIterator {
private Node current = null;
public synchronized void resetToHead() {
current = head.next;
}
public synchronized void resetToTail() {
current = tail.prev;
}
public synchronized E get() {
if (current!=null) return current.data;
return null;
}
}
}
the problem is that i get the following compilation Error on the emphasized lines :
> Type mismatch: cannot convert from LinkedList<E>.Node<E> to
> LinkedList<E>.Node<E>
what does it mean? and how do i fix this?
btw, the code is only part of the implementation so dont try to logicly figure it out.
--- Edited as the question changes slightly ---
The question is now becoming, how do I have two inner classes coordinate generic types? In short, they don't have to if they are both inner classes of an outer class where the generic type is bound. So even with the public synchronized E get() in the non-generic LinkedListIterator you are returning an E (and it is type safe).
However, if you then reach out to implement java.util.Iterator<E> things fall apart, because that E is based on a different class (interface) so the E has different scoping. How do you fix this? You need to parameterize your Node classes to Node<E> to satisfy that E bindings exist on the implementation of Iterator even when that implementation is being used outside of the scope of it's originating class. This forces Node<E> to be defined statically.
The reason it forces the static definition of Node<E> has to do with garbage collection. An Iterator might still be holding references to Nodes even though the LinkedList is scheduled for garbage collection. Sure, you might be able to keep such a thing from happening with a specific implementation, but the JVM has to allow any implementation (even an errant one).
Perhaps it is easier to explain with code
public LinkedList<E> {
public Iterator<E> iterator() {
return new LinkedIterator(head);
}
// private because we don't want instances created outside of this LinkedList
private class LinkedIterator implements Iterator<E> {
// Right here, needing a parameterized next node will force Node to be static
// static inner classes can exist outside of the scope of their parent
// Since it can exist outside of the parent's scope, it needs it's own generic parameter
private Node<E> next;
LinkedIterator(Node start) {
next = start;
}
public boolean hasNext() {
return next != null;
}
public E next() {
Node<E> retValue = next;
if (retValue != null) {
next = retValue.next;
}
return retValue;
}
}
// must be static because LinkedList might be garbage collected when
// an Iterator still holds the node.
// This E is not the same E as in LinkedList, because it is a E declaration (hiding the above E)
private static Node<E> {
Node<E> next;
Node<E> prev;
E data;
}
}
If you are not careful, you can now wind up back where you started; however, the key is to construct new Node<E> objects when needed in the parent scope. Since that is the same scope where you construct LinkedIterator types, the generic type safety will be ensured.
--- Original post follows ----
By specifying that your node class definition is a Node<E>, you basically create a second, independently scoped generic type E which will hide the outer generic type E in the LinkedList class.
Since none of your classes are static, they will only exist within context of a LinkedList class, which will provide the generics binding. That means you can simplify Node<E> to Node yet still put E class types within the Node class. Same goes for the LinkedListIterator, except that if you want it to implement Iterator you should indicate it implements Iterator<E>.
Due to request, what follows is the code that compiles on my machine, (java 1.6.0_20)
public class LinkedList<E> {
private class Node {
protected Node next, prev;
protected E data;
protected Node(E dat) {
data = dat;
next = prev = null;
}
}
private Node head, tail;
public LinkedList() {
(head = new Node(null)).next = tail = new Node(null);
tail.prev = head;
tail.next = head.prev = null;
}
public class LinkedListIterator {
private Node current = null;
public synchronized void resetToHead() {
current = head.next;
}
public synchronized void resetToTail() {
current = tail.prev;
}
}
}
You overdid it a bit by parametrising the embedded classes. I removed all unnecessary ones.
public class LinkedList<E> {
private class Node {
protected Node next, prev;
protected E data;
protected Node(E dat) {
data = dat;
next = prev = null;
}
}
private Node head, tail;
public LinkedList() {
(head = new Node(null)).next = tail = new Node(null);
tail.prev = head;
tail.next = head.prev = null;
}
public class LinkedListIterator {
private Node current = null;
public synchronized void resetToHead() {
current = head.next;
}
public synchronized void resetToTail() {
current = tail.prev;
}
}
}
Alternatively with a static class Node.
public class LinkedList<E> {
private static class Node<E2> {
protected Node next, prev;
protected E2 data;
protected Node(E2 dat) {
data = dat;
next = prev = null;
}
}
private Node<E> head, tail;
public LinkedList() {
(head = new Node(null)).next = tail = new Node(null);
tail.prev = head;
tail.next = head.prev = null;
}
public class LinkedListIterator {
private Node<E> current = null;
public synchronized void resetToHead() {
current = head.next;
}
public synchronized void resetToTail() {
current = tail.prev;
}
}
}
It doesn't understand that the <E> in LinkedListIterator is the same <E> as the parent class. Just remove from the inner class:
public class LinkedListIterator {
private Node<E> current = null;
public synchronized void resetToHead() {
current = head.next;
}
public synchronized void resetToTail() {
current = tail.prev;
}
}

Categories