Home > Enterprise >  Java object contains list of other objects. how to create object with empty list instaed of null
Java object contains list of other objects. how to create object with empty list instaed of null

Time:11-08

I have below code sample, if i create Cart object , im getting Items list as NULL.

@Data
class Cart{
    int cartId;
    List<Item> items;

}

@Data
class Item{
    int itemId;
    String itemName;
}


public class Test {

    public static void main(String[] args) {
        Cart cart = new Cart();
        System.out.println(cart); // Cart(cartId=0, items=null)
    }
}

How can i create Cart object with Items as empty list {}, instead of NULL.

If my class has 10 no.of List Items, How can we create Cart Object with empty list.

Can we create with ObjectMapper or any other API ?

CodePudding user response:

Override public no argument constructor to initialize the variable

Public Cart(){     
  this.items=new ArrayList<>();
}

or have a default value

@Data
class Cart{
    int cartId;
    List<Item> items=new ArrayList<>();;
}

CodePudding user response:

You have 2 options:

new Cart("id", new ArrayList<>()); // items is mutable
new Cart("id", List.of()); // items is immutable

or set default values:

@Data
class Cart{
    int cartId = 0;  // optional, because int is 0 by default  
    List<Item> items = new ArrayList<>();
}

You use Lombok. In case you have such questions, I reccomend you not to use it for a while.

  • Related