-1

I'm new to list, but I'm trying to return an empty list through a method, so that list can be used somewhere else. But I don't know how to do it.

public List<Something> login (String user, String key){
    if (success) {
        System.out.println("Welcome");
        return  (THIS IS WHERE I WANT TO RETURN AN EMPTY LIST);
    } 

    System.out.println("Incorrect Information");
        return null;
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
JMM
  • 53
  • 1
  • 8

3 Answers3

4

If you are going to use it somewhere else, you can return any implementation of List interface. The most used:

new ArrayList<>();

Also there are a few ways to return an immutable empty list (means that you can not modify it):

return Collections.emptyList();
return List.of();  // from java9

See difference between them List.of() or Collections.emptyList()

Also see more about List implementations

Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • Worth noting emptyList() and of() returns two different types of List (they're a bit different in the implementation). – LppEdd Mar 12 '19 at 21:00
3

How about:

return new ArrayList<>();
Andronicus
  • 25,419
  • 17
  • 47
  • 88
2

java.util.List is an interface and therefore you cannot instantiate one.

You should instantiate one of it's implementation classes and return that object.

Like return new ArrayList<>();

Some random IT boy
  • 7,569
  • 2
  • 21
  • 47