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 want to create a list of options for testing purposes.

(我想创建用于测试目的的选项列表。)

At first, I did this:

(首先,我这样做:)

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then I refactored the code as follows:

(然后,我将代码重构如下:)

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?

(有一个更好的方法吗?)

  ask by Macarse translate from so

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

1 Answer

It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?

(如果仅将其声明为List ,则将更简单-它必须是ArrayList吗?)

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

Or if you have only one element:

(或者,如果您只有一个元素:)

List<String> places = Collections.singletonList("Buenos Aires");

This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

(这意味着places不变的 (尝试更改位置将导致引发UnsupportedOperationException异常)。)

To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:

(要创建一个具体的ArrayList可变列表,您可以从不可变列表创建ArrayList :)

ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

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