1 Reply Latest reply: Mar 12, 2013 12:07 PM by jtahlborn RSS

    What's Empty List Good For?

    aksarben
      I'm having a hard time understanding the point of an empty list. The following code doesn't let me add anything to the list:
      public static void main(final String[] args) {
      
         final List<String> mammalList = Collections.emptyList();
         mammalList.add("Dog");
         mammalList.add("Cat");
      
         final List<String> fishList = Collections.emptyList();
         fishList.add("Shark");
         fishList.add("Grouper");
      
         System.out.printf("Mammals: %s%n", mammalList);
         System.out.printf("Fish: %s%n", fishList);
      }
      Gives Exception in thread "main" java.lang.UnsupportedOperationException
           at java.util.AbstractList.add(Unknown Source)
           at java.util.AbstractList.add(Unknown Source)
           at Test.main(Test.java:16)

      So, if you can't use the empty list, why have it in the first place? Why not just say
       List<String> mammalList = new ArrayList<String>();
      What's the added value of EMPTY_LIST? What am I missing here?
        • 1. Re: What's Empty List Good For?
          jtahlborn
          It's useful for return values from methods where the caller is not expecting a modifiable list.
          public List<String> findSomeStuff() {
            // ... do search here ...
            if(!foundResults) {
              return Collections.emptyList();
            }
            // ... return real results
          }
          It's also useful for simplifying subsequent code without having to deal w/ null values.
          List<String> results = getSomeResults();
          if(results == null) {
            results = Collections.emptyList();
          }
          
          // process "results" knowing it is not null
          for(String result : results) {
          }
          In both of these cases i don't need to instantiate a new list ("emptyList()" returns an single existing instance).