Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am learning Spring and I read the Spring in Action book. I wonder if you are supposed to inject an empty arraylist (if that is possible) or create it like the example below?

public class StackOverflow {

    private List<Car> cars;

    public StackOverflow() {
        cars = new ArrayList<Car>();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
731 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can inject an empty list like this, however this is probably unnecessary, unless you're trying to setup an example template spring XML config perhaps.

<property name="cars">
  <list></list>
</property>

If you want a quick way of setting empty lists to prevent null pointer problems, then just use Collections.emptyList(). You can also do it "inline' as follows. Note though that Collections.emptyList() returns an unmodifiable list.

public class StackOverflow {

    private List<Car> cars = Collections.emptyList();

You'll also need getters and setters for cars to be able to use it from spring XML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...