check if an object is null - java

I have a linked list in which first node contains null object. means firstNode.data is equal to null, firstNode.nextPointer = null, firstNode.previousPointer = null.
And I want to check if firstNode is null or not.
So I tried-
if(list.firstNode == null){
//do stuff
}
but this doesn't works?
I also tried equals too. Any suggestions?
I tried printing. And I got as-
{null} -- firstNode

I think your firstNode is not null, but its fields are. Try something like this:
if (list.firstNode.data == null) {
//do stuff
}

Did you try
if (list.firstNode.data == null) { /* Do stuff */ }

You checking for list.firstNode being null. Do you mean to check for
list.firstNode.data==null

The answer is in the question. You said:
have a linked list in which first node contains null object. **means firstNode.data is equal to null**,
This means you should do the following instead:
if(list.firstNode.data == null){
//do stuff
}

It seems to me that your question is related to the processing of a doubly-linked list.
To check if empty use: (list.firstNode.next == list.firstNode.previous) this is true for an empty doubly linked list.

You can check if all the fields of the node are null:
Node firstNode = list.firstNode;
if(firstNode.data == null &&
firstNode.nextPointer == null &&
firstNode.previousPointer == null) {
//Do stuff
}
Or to prevent code repetition, you can either create an instance method isNull() to do the test or create a NULL object and override the equals method in your Node class to check if a node is equal to the null node as you described.
class Node<E> {
//The null node, assuming your constructor takes all three values.
public static final Node NULL = new Node(null, null, null);
//Fields here with constructors etc.
#Override
public void equals(Object obj) {
if(!obj instanceof Node) return false;
Node<?> node = (Node<?>)obj;
if(node.data.equals(this.data) &&
node.nextPointer == this.nextPointer &&
node.previousPointer == this.previousPointer) {
return true;
} else {
return false;
}
}
Then when you want to check if a node is null you can do:
if(list.firstNode.equals(Node.NULL)) {
//Do stuff
}

Related

Question on overriding equals & calling equals recursively

So I overwrote an equals function that works with Nodes that contain objects. and it looks like this.
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
// Checks if obj is from the same class as this Deque.
if (obj.getClass() != this.getClass()) return false;
#SuppressWarnings("unchecked")
// If obj is from the same class, casts object to DoublyLinkedDeque.
DoublyLinkedDeque<T> object = (DoublyLinkedDeque<T>) obj;
Node other = object.front;
Node self = this.front;
// Checks the info of every Node in this Deque with the other.
while (self != null && other != null) { // Checks
if (!(self.info.equals(other.info))) return false;
self = self.next;
other = other.next;
}
// Otherwise, checks if the front of both Deques is null.
return (self == null && other == null);
}
And it works but I'm not sure how the second invocation of equals work. Specifically how does my code check if the info field (that contains objects) of two nodes are equal without calling super.equals? Nothing in my function has the capability to check if two objects are equal as far as I know, can someone explain this?

search and remove a node from linked list

I am using a linked list without using collections class for data structure practice.
I wanted to remove an element from the linked list after passing the element value to function
This is the function that i've written.
public boolean remove(String s)
{
if(head.getName().equalsIgnoreCase(s))
{
head = head.getNext();
return true;
}
else
{
Node p =head;
Node current=p.getNext();
while(true) {
if(current == null || current.getName().equals(s)) {
break;
}
p = current;
current = current.getNext();
}
if (current == null)
{
p.setNext(current.getNext());
return true;
}
}
return false;
}
i'm using Node p to store the previous node and current node.
The code falls in the return false section and there is no change in the list.Also i'm getting a null pointer exception warning in the p.setNext(current.getNext()) here.
Please let me know where i'm making mistake.
Regarding the Null Pointer Exception this should ring a bell
if (current == null)
{
p.setNext(current.getNext());
return true;
}
current is null and you are trying to invoke a method from it.
Also it doesn't seem you handle the corner cases like the list is empty or having one element.
current == null
is the not found case. When current == null we should return false, and calling current.getNext() will give the null pointer error. Similarly, the found case is not getting into the block you want. It should suffice, I think, to say if (current != null) where you have if (current == null)
I found https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/ helpful.
Instead of checking true condition based on current value which possibly may or may not be null, you should be having one boolean flag.
This flag value can be made true if you find the passed element.
while(true) {
if(current == null || current.getName().equals(s)) {
flag = true;
break;
}
p = current;
current = current.getNext();
}
if (flag)
{
if(current!=null)
p.setNext(current.getNext());
return true;
}

How to check if Iterator.next() is == null?

How do I check if the next element in the list is null ?
while(it.hasNext()){
System.out.println(it.next()+"\n");
}
this is how I tried, but when the last element is null it prints it as null.
I tried to change it
while(it.hasNext()){
if(it.next()==null){
}else
System.out.println(it.next()+"\n");
}
but this just makes it worst because some of the elements don't even print!
This is my Iteration method/anonymous class
public Iterator<Filmi> iterator3DFilms ()throws FilmiException{
if(filmList.isEmpty())
throw new FilmiException("No Films on the list");
return new Iterator<Filmi>(){
private int index=0;
public boolean hasNext(){
return index <filmList.size();
}
public Filmi next(){
Filmi lb = filmList.get(index++);
if(lb.is3D()== true)
return lb;
if(hasNext())
return next();
return null;
}
public void remove(){}
};
}
The null print only happens at the last element
Thank you.
Naturally, code like
if (it.next() == null){
} else {
System.out.println(it.next()+"\n");
}
will consume every other non-null element, as you are observing. Plus calling it.next() without checking it.hasNext() is a recipe for disaster.
Why not write
Foo/*ToDo - use the correct type here*/ foo = it.next()
if (foo != null){
/*ToDo*/
}
instead?
No it cannot work this way because if it.next() is not null you call it.next() twice which will make you skip a value that could not even be available.
Use a variable instead as next:
Object o = it.next();
if (o != null) {
...
}
you should use stream instead of iterator.
filmList.stream().filter(film->film!=null).filter(film->film.is3D())
Edit:
or, if you'r not in Java 8 :
Predicate<Film> isNotNullAnd3D = new Predicate<Person>() {
public boolean apply(Film f) {
return f != null && f.is3D();
}
};
Collection2.filter(filmList, isNotNullAnd3D)
You never mentioned why you use iterators explicitly in the first place.
Why not use implicit iterator notation like this ? :
for (Film film : filmList) {
if (film != null ){
....
}
}
Additionally to what others said: in case you are doing a for-each loop with a primitive type like int
for (int node : input) {
doSomething(node);
}
you might want to consider using the Wrapper class instead:
for (Integer node : input) {
if (node == null) throw new IllegalArgumentException();
doSomething(node);
}

Adding a object to a linked list at the end but always resulting into an error when a 2nd object is passed thru

I'm working on this method with linked list.
It's a method that add's an object at the end of the list.
I've got a problem when adding a second object in the linked list.
It gives me a NullPointerException at the while :
while (this.actual.getNext() != null)
I can't see what's wrong and i've been on this for an hour doing junits tests.
Any help ?
here's the complete code :
public boolean addEnd(T element) {
boolean res = false;
this.actual = this.head;
if (element != null) {
if (this.actual == null) {
this.head= new Node<T>(element);
res = true;
nbElm++;
} else if (!hasElement(element)) {
while (this.actual.getNext() != null) { //Gives me an error NullPointeException
this.actual = this.actual.getNext();
}
Node<T> next = new Node<T>(element);
this.actual.setNext(next);
res = true;
nbElm++;
}
}
return res;
}
Looking at this addEnd method, I think this.actual has no reason of being an instance variable. It should be a local variable of the method. Being an instance variable may cause other methods that use it to interfere with addEnd. I'm guessing hasElement modifies this variable, causing this.actual to become null before the start of your while loop.

Issue with Object Comparison in Java (Context is RB Tree)

High, I'm mostly familiar with C & C++ but I've been trying my hand at java recently.
My issue is that line if (parent.leftChild == temp) is never true. Although parent.leftChild.Key = temp.key (and the rest of the contents are the same), I'm under the impression that the issue is that parent.leftChild's ID in Eclipse's debugger = ...5792 while temp's ID is ...3632.
I was hoping that someone could further explain. A workaround to my code can always be to change the if statement to if (parent.leftChild.key = temp.key), but shouldn't parent.left == temp be valid?
class Node{
int key;
char color;
Node leftChild;
Node rightChild;
Node parent;
//...constructors..//
}
private Node GetParent(Node node){
if(node != null)
return node.parent;
else
return null;
}
private void RemoveNodeFromTree(Node myNode){
Node temp = new Node(myNode);
//traverse
if(temp.leftChild!= null){
temp = temp.leftChild;
while(temp.rightChild!= null)
temp = temp.rightChild;
myNode.key = temp.key;
}
else if(temp.rightChild != null)
myNode.key = temp.rightChild.key;
Node parent = GetParent(temp);
Node childL = temp.leftChild;
Node childR = temp.rightChild;
//have parent point to the proper new node.
//parent points to left if it exists, then it tries right.
//if both are null, point to right anyway
if(parent !=null ){
//replace temp with it's left child
if(childL!= null){
if (parent.leftChild == temp)
parent.leftChild = childL;
else
parent.rightChild = childL;
childL.parent = parent;
childL.color = 'B';
if(childL.color == 'B' && temp.color == 'B')
DoubleBlackRestructure(childL, parent);
}
else //replace temp with it's right child
{
if (parent.leftChild == temp)
parent.leftChild = childR;
else
parent.rightChild = childR;
if(childR!= null)
childR.parent = parent;
if((childR == null || childR.color == 'B') && temp.color == 'B')
{
if(childR != null)
childR.color = 'B';
DoubleBlackRestructure(childR, parent);
}
else if (childR != null)
childR.color = 'B';
}
}
else
myNode = null;
temp = null;
}
Every object in Java represents a reference type. Typically, a reference is the memory address at which the object or array is stored. However, since Java references are opaque and cannot be manipulated in any way, this is an implementation detail. Therefore Java doesn't really have pointers like C++ but it has references to objects.
As for your problem, using the workaround you suggested should be the easiest and simplest way to solve your problem. However, if you want to compare objects in Java in general, here is how you do it.
Java has two kinds of object equality:
Object reference equality : when two object references point to the same object.
if (obj1 == obj2) {
// The two object references point to the same object
}
Object value equality : when two separate objects happen to have the same values/state.
if(obj1.equals(obj2)) {
// two object references contain "equal" objects
}
The reason "equal" is in quotes is because it is up to us to say when exactly are two objects equal.
To be able to value-compare two Java objects of the same class, the boolean equals(Object obj) method must be overridden and implemented by the class.
Note that equal objects must have equal hash codes. Therefore, when overriding the equals method, we must also override the hashCode method. Failure to do so violates the general contract for the hashCode method, and any classes that use the hash code, such as HashMap will not function properly.
We decide which values must be equal to consider two objects to be equal. In your case, you could just override the equals() method without the hashCode since you are not putting Node objects in any containers that require a properly implemented hashCode but you should be aware of the possible consequences. The equals() method inside the Node class could compare nodes based on their keys and would look something like:
class Node {
int key;
char color;
Node leftChild;
Node rightChild;
Node parent;
//...constructors..//
boolean equals(Object obj) {
//null instanceof Object will always return false
if (!(obj instanceof Node)) {
return false;
}
// each object is obviously equal to itself
if (obj == this) {
return true;
}
return this.key == ((Node) obj).key;
}
/* This is a simple example of how to override the hashCode as well.
public int hashCode() {
// some code to represent each node uniquely
// i just assume each node has a unique key
return this.key
}
*/
}
Then you can just use the following statement in your code:
if (parent.leftChild.key.equals(temp.key))
The advantage of using equals() implementation is that you can define object equality in many specific ways so it is a quite flexible solution.
Here is a good stackoverflow thread on this
Here is another useful read

Categories