How do i compare an object with null? From what i've seen right now, at execution an NullPointerException will be thrown :S
For example, if I have a list:

class List
{
	private Node data;
	private Lista urm;
	
	public List(Node d,Lista u)
	{
		data = d;
		urm = u;
	}
	
	public List(Lista l)
	{
		this.data = l.data;
		this.urm = l.urm;
	}

	public Node getData()
	{
		return data;
	}
	
	public Lista getUrm()
	{
		return urm;
	}
	
	public void setData(Node d)
	{
		data = d; 
	}
	
	public void setUrm(Lista u)
	{
		urm = u;
	}
}

, and in another class i have:

class Node {
...
private Lista child;
...

public void addChild(Node c)
{
	if(child.getData().equals(null)) child = new Lista(c,null);
	else child.setUrm(new Lista(c,null));
}
}

the NullPointerException error will occur at

if(child.getData().equals(null))

I really have to make that check, otherwise my first element of the list will always be null.

Any suggestion appreciated :)

Recommended Answers

All 4 Replies

You'd compare an object to null with == . I think you want one of the following. It's hard to determine the exact behavior you're looking for from your code.

if (child == null)
    child = new Lista(c, null);

// Or:

if (child.getData() == null)
    child = new Lista(c, null);

Thanks, I first thought the "child == null" condition still doesn't work but I later saw that the error came from the else statement.

Cheers :)

Hi I am trying to make the same thing, but I get a NullPointException:
I have tried with:

r[a].toString.equals(null);
r[a]==null;
r[a].equals(null);

and all the time I get a NullPointException

r = (Object[]) list.get(i);
for (int a = 0; a < r.length; a++) {  if (r[a] == null) {
dos.writeChars("empty");

What can I do?

Thank you in advance

Check if 'r' or 'dos' isn't a null also.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.