Hi, I've got a method that returns 'null' for a linked list

public LinkedList<names> Relate(names Student)  {
		return null;

How can i get it to return an empty List, so that I dont get a null pointer exception?

Thanks in advance,

Recommended Answers

All 3 Replies

null value represents the empty list

if(Relate(names Student) == null)
        //empty list
        //not empty

Well, turingmachine completely ignored the question.

Just return an empty list

return new LinkedList<names>();

or you could also define an empty list class constant to use for that purpose

public final static LinkedList<names> EMPTY_LIST = new LinkedList<names>();

A couple of additional thoughts:
- Do you really need to return a LinkedList? It's usually better to use the interface List, so as not to nail yourself to using a particular list class.
- Why is "names" lowercase? Class names should begin with a capital.
- The EMPTY_LIST should probably be unmodifiable unless you explicitly expect callers to add data to that list, which is probably not a good idea anyway

public final static List<names> EMPTY_LIST = Collections.unmodifiableList(new LinkedList<names>());

I'm so sorry.
I misunderstood the question.

Ezzaral was right.
For the simplest way, you can just put/add this to the method:

return new LinkedList<names>();

please disregard my previous reply.
null can equate to an empty list but it represents more to a non-existing list/"value" :)

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.