Follow us

May the source be with you!

Blog about the light side of the *.java

  • Home
  • Java
  • JavaFX
  • Spring
  • JavaScript
  • About me
  • Contacts
    • via mail
    • twitter
    • facebook
Home Archive for July 2010

It is little strange that no one really uses emptyList like he should in Java.
So this is small post showing how to use the emptyList method in the Collections class.

Question: How to create an empty list ?
lets assume that we have a class Book with multiple titles.
So the class in our examples will be:

import java.util.List;

public class Book {

      private List<String> titles;

      public void setTitles(List<String> titles) {

            this.titles = titles;

      }

      public List<String> getTitles() {

            return titles;

      }

}

Lets say that in our snippet we have something like :

  Book myCrazyBook=new Book();

and we want to assign an empty list to the titles in this book. This is a common scenario if you want to set something to be emptyList in specific case instead of null.

So of course your first try will be something like:
Answer 1:

  myCrazyBook.setTitles(new ArrayList()); 

-WARRNING - ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

Ok changing to:

  myCrazyBook.setTitles(new ArrayList<String>());   

WTF ? the problem in this answer is not small one :
- you are creating empty ArrayList which basiclly is not needed. ( what if you are in a loop 1000+ empty ArrayLists ? )

Answer 2.

   myCrazyBook.setTitles(Collections.EMPTY_LIST);

-WARNING : Type safety: The expression of type List needs unchecked conversion to conform to List<String>, because the EMPTY_LIST is raw type, which was heavily used before Java 1.5.
The definition of this list is :

    /**

     * The empty list (immutable).  This list is serializable.

     *

     * @see #emptyList()

     */

    public static final List EMPTY_LIST = new EmptyList();

So you see it is not ArrayList or LinkedList or MyCrazyCustomListWhichIUseEveryWhereList.

Answer 3:
Eclipse will tell you this answer : Replace with Collections.emptyList();

      myCrazyBook.setTitles(Collections.emptyList());

COMPILE TIME ERROR: why ? because emptyList invoked like that means List of Objects not List of String. The other thing is that you cannot cast to List<String> because you cannot cast List<Object>  to List<String>.

Answer 4:
You know that there is Collections.emptyList() AND YOU KNOW THAT IT RETURNS List<T>
so your answer is:

            Book myCrazyBook=new Book();

            List<String> titles = Collections.emptyList();

            myCrazyBook.setTitles(titles);

           

And this will work WITHOUT any WARNINGS or ERRORS. The type of the List is taken from the type of the variable that you are trying to assign to.
Of course why you need this local variable ? I want to remove it it is not needed and used, but if you remove it you are in Answer 3. So what can you do ?

Answer 5: The right but strange looking answer.

            Book myCrazyBook=new Book();

            myCrazyBook.setTitles(Collections.<String>emptyList());

Yes this is not a joke there is a dot (.) then the generic type before the method name. This compiles, runs, no warnings thats the real way.
It is a little strange that most people dont know this aspect of generics in Java even I didn't know it, I was thinking that you cannot pass a generic type like this but as it looks you can.

So if you have some static method like this one:

public class Main{

      public static <G> List<G> someGreatMethod(){

            List<G> gList= new ArrayList<G>();

            return gList;

      }

}

you can invoke it with Main.<String>someGreatMethod(); for example.
Subscribe to: Posts ( Atom )

ABOUT AUTHOR

Superhero with Java powers && Gamer && (Sci-Fi & Star Wars geek) && Bulgarian Java User Group Leader && nerds2nerds podcaster && (link: http://java.beer) java.beer guy ? this : null

Social

Twitter
Facebook

LATEST POSTS

  • Use Client Certificate Authentication with Java and RestTemplate
    As a follow up of the  http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html  we now have a keystore and a truststo...
  • Convert PFX certificate to JKS, P12, CRT
    I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert i...
  • Use Multiple JVM versions on Mac OS and Linux
    Linux Download multiple Java versions and put them into /opt/ If you already have some JDK from ubuntu repo or etc not a big deal, just f...
  • Hibernate Generic DAO.
    When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a...
  • Youtube video channel of the Bulgarian Java User Group
    Bad news everyone, as you already have noticed I do not have time to write blogs :( However I would recommend you to check and keep an ey...
  • Patching a Maven library with your custom class.
    Sometimes you use a library that has a bug. Or maybe it doesn’t has a bug but you want to change something. Of course if it is an open sourc...
  • RichFaces server-side paging with DataTable.
    Most of the component toolkits have build in support for server-side paging this days but in rest of the cases you need to customize a littl...
  • JSF, RichFaces, Spring, Hibernate – lets make development easy.
    The goal of this article is to show you how you can use Hibernate, Spring and JSF 1.2 in the most easiest way. Used technologies : ma...
  • spring-loaded rocks !
    Today I found spring loaded ( https://github.com/spring-projects/spring-loaded ) in short this is a java agent that enables class reloading...

Categories

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

What I read ?

  • Baeldung
  • Java Code Geeks
  • Vlad Mihalcea
  • Javarevisited
  • Pushing Pixels
  • Vanilla #Java
  • Antonio's Blog
  • Oracle Blogs | Oracle The Aquarium Blog
  • JavaWorld
  • blog@CodeFX
  • Jonathan Giles
  • JavaFX News, Demos and Insight // FX Experience
  • Eclipse Papercuts
  • Codedependent
  • Caffeine Induced Ramblings - Jasper Potts's Blog
  • Joshua Marinacci's Blog

Search This Blog

Blog Archive

  • November 2019 (2)
  • July 2019 (1)
  • April 2019 (2)
  • February 2019 (1)
  • January 2019 (1)
  • May 2016 (1)
  • October 2015 (1)
  • September 2015 (1)
  • June 2015 (2)
  • May 2015 (2)
  • February 2015 (1)
  • October 2014 (1)
  • July 2014 (2)
  • April 2014 (1)
  • June 2013 (1)
  • July 2011 (2)
  • May 2011 (1)
  • March 2011 (1)
  • July 2010 (1)
  • June 2010 (1)
  • October 2009 (3)
  • September 2009 (6)
  • August 2009 (9)
  • June 2009 (1)
Powered by Blogger.

Blog info

My photo
jNayden
View my complete profile

About us

Labels

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

Advertisement

Popular Posts

    no image Use Client Certificate Authentication with Java and RestTemplate
    no image Convert PFX certificate to JKS, P12, CRT
    no image Use Multiple JVM versions on Mac OS and Linux
    no image Hibernate Generic DAO.
    no image Youtube video channel of the Bulgarian Java User Group
    Patching a Maven library with your custom class. Patching a Maven library with your custom class.
    RichFaces server-side paging with DataTable. RichFaces server-side paging with DataTable.
    no image JSF, RichFaces, Spring, Hibernate – lets make development easy.
    no image spring-loaded rocks !

FOLLOW US @ INSTAGRAM

About Me

  • Normal Link 01
  • Normal Link 02
  • Custom Menu 01
  • Custom Menu 02
  • Disclaimer
  • Terms
  • Policy
  • Home
  • About
  • Contact
  • Home
  • Features
  • _Multi DropDown
  • __DropDown 1
  • __DropDown 2
  • __DropDown 3
  • _ShortCodes
  • _SiteMap
  • _Error Page
  • Documentation
  • _Web
  • _Video
  • Download This Template

Menu Footer Widget

  • Home
  • About
  • Contact

Social Plugin

Tags

Advertisement

Responsive Advertisement
May the source be with you!

Popular Posts

java

Convert PFX certificate to JKS, P12, CRT

Use Client Certificate Authentication with Java and RestTemplate

Use Multiple JVM versions on Mac OS and Linux

Hibernate Generic DAO.

Copyright 2014 May the source be with you!.
Blogger Templates Designed by OddThemes