Why collection literals?

前端 未结 11 859
无人及你
无人及你 2020-12-29 04:09

From the various online articles on Java 7 I have come to know that Java 7 will be having collection literals1 like the following:

List

        
11条回答
  •  一向
    一向 (楼主)
    2020-12-29 05:07

    IMO this is just a Syntactic sugar that simplifies code a bit. Why are you not surprised by a sugar of the same kind:

    int []arr1 = new int[] {1,2,3};
    int []arr2 = {1,2,3};
    

    It is just a convenient way to express a simple idea instead of writing something like

    int []arr = new int[3];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    

    Does this add something really new to our life? Well, no. Does it makes our lives a bit easier? I think, yes.

    Regarding second part of question, I don't know what actual types would be. But frankly speaking, how often do you care what collection implementation is? Especially taking into account that such collections are expected to be relatively small (with all values typed by a developer). Anyway, in those rare cases when you do care, just don't use this simplified syntax and do the job yourself.

提交回复
热议问题