Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collection property initialisation - best practice

Tags:

java

Age old problem, but what's the best practice here?

Four examples off the top of my head:

//================
public class POJO{
  List<String> list;
}

//================
public class POJO{
  List<String> list = new ArrayList<String>();
}

//================
public class POJO{
  List<String> list;

  public POJO(){
    list = new ArrayList<String>();
  }
}

//================
public class POJO{
  List<String> list;

  public getList(){
      if (list==null)
        list =new ArrayList<String>();
      return list;
  }
}

I'm asking because I've got client facing POJOs that initialise to null and domain objects that are returning empty collections when they query the database and miss (but they will insert nulls). I think I need to do one or the other but can't decide which.

like image 731
tom Avatar asked Oct 25 '13 10:10

tom


Video Answer


1 Answers

The second one:

public class POJO {
    List<String> list = new ArrayList<String>();
}
like image 187
Adam Stelmaszczyk Avatar answered Nov 15 '22 00:11

Adam Stelmaszczyk