0

When I read some open source java projects, I found that there are two ways to declare a static list variable with a default value in the class.

Is there any difference between these two methods? (performance, pros or cons)

  1. initialize Map object with all the initial values along with declaration:
public class OrderStatusHandler {

    private static final Map<Integer, String> ORDER_STATUS = new HashMap<Integer, String>() {{
        ORDER_STATUS.put(0, 'UNPAID');
        ORDER_STATUS.put(1, 'PAID');
        ORDER_STATUS.put(2, 'FINISH');
    }};
    
    ...
}
  1. initialize List object with static block:
public class OrderStatusHandler {

    private static final Map<Integer, String> ORDER_STATUS = new HashMap<Integer, String>();
    
    static {
        ORDER_STATUS.put(0, 'UNPAID');
        ORDER_STATUS.put(1, 'PAID');
        ORDER_STATUS.put(2, 'FINISH');
    }
    
    ...
}
lucaYeung
  • 1
  • 2
  • The duplicate focuses on your first answer, but also gives some context on your second one. **tl;dr** try to avoid the first one and replace the second one with [simply `Map.of`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#of(K,V)) (available since Java 9) – Joachim Sauer Aug 04 '21 at 08:16

0 Answers0