etc./StackOverFlow

한 줄에 ArrayList 초기화

청렴결백한 만능 재주꾼 2021. 10. 27. 23:23
반응형

질문자 :Macarse


테스트 목적으로 옵션 목록을 만들고 싶었습니다. 처음에는 이렇게 했습니다.

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

그런 다음 코드를 다음과 같이 리팩토링했습니다.

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

이 작업을 수행하는 더 좋은 방법이 있습니까?



List 로 선언하면 더 간단할 것입니다. ArrayList여야 합니까?

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

또는 요소가 하나만 있는 경우:

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

places변경 불가능 함을 의미합니다(변경하려고 하면 UnsupportedOperationException 예외가 발생함).

ArrayList 변경 가능한 목록을 만들려면 변경할 수 없는 목록에서 ArrayList 를 만들 수 있습니다.

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

Tom

ArrayList 를 초기화하는 "가장 좋은" 방법은 사용자가 작성한 방법일 것입니다. 어떤 식으로든 List

 ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C");

list 인스턴스를 참조하는 데 필요한 입력이 상당히 많다는 것입니다.

인스턴스 이니셜라이저("이중 중괄호 초기화"라고도 함)를 사용하여 익명 내부 클래스를 만드는 것과 같은 대안이 있습니다.

 ArrayList<String> list = new ArrayList<String>() {{ add("A"); add("B"); add("C"); }};

그러나 나는 그 방법을 그다지 좋아하지 않습니다. 왜냐하면 당신이 끝내는 ArrayList 의 하위 클래스이고, 그 클래스는 단지 하나의 객체를 생성하기 위해 생성되기 때문입니다. .

Project Coin 에 대한 Collection Literals 제안 이 수락되었다면 좋았을 것입니다(Java 7에 도입될 예정이었지만 Java 8에도 포함될 가능성은 없습니다.).

 List<String> list = ["A", "B", "C"];

ArrayList 아닌 List 를 초기화하기 때문에 여기에서는 도움이 되지 않을 것이며, 더군다나 가능하다면 아직 사용할 수 없습니다.


coobird

간단한 대답

자바 10 이상:

 var strings = List.of("foo", "bar", "baz");

이렇게 하면 변경할 수 없는 List 가 제공되므로 변경할 수 없습니다.
미리 채우는 대부분의 경우 원하는 것입니다.

자바 9

Java 9를 사용하는 경우 var 키워드를 사용할 수 없습니다.

 List<String> strings = List.of("foo", "bar", "baz");

자바 8 이하:

 List<String> strings = Arrays.asList("foo", "bar", "baz");

이것은 List *를 제공하므로 길이를 변경할 수 없습니다.
List.set(...) 호출할 수 있으므로 여전히 변경 가능 합니다.

* ArrayList 라는 java.util.Arrays 내부의 비공개 중첩 클래스입니다.
이는 단순한 이름이 같더라도 java.util.ArrayList 와 다른 클래스입니다.

정적 가져오기

정적 가져오기를 사용하여 Arrays.asList 더 짧게 만들 수 있습니다.

 import static java.util.Arrays.asList; ... List<String> strings = asList("foo", "bar", "baz");

모든 최신 IDE * 가 이를 제안하고 수행합니다.

나는 정적으로 수입하지 않는 것이 좋습니다 List.of 것과 같이 방법을 of 이 혼란 있기 때문에.

* 예를 들어 IntelliJ IDEA에서 Alt+Enter 를 누르고 Static import method...

Stream 사용하기

List 이어야 합니까?
Java 8 이상에서는 보다 유연한 Stream

 Stream<String> strings = Stream.of("foo", "bar", "baz");

Stream 을 연결할 수 있습니다.

 Stream<String> strings = Stream.concat(Stream.of("foo", "bar"), Stream.of("baz", "qux"));

Stream 에서 List 이동할 수 있습니다.

 import static java.util.stream.Collectors.toList; ... var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16 List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8

그러나 바람직하게는 Stream List 수집하지 않고 Stream을 사용하는 것이 좋습니다.

java.util.ArrayList 가 필요한 경우 *

둘 다 미리 채울하려는 경우 ArrayList 나중에 그것을 추가 사용

 List<String> strings = new ArrayList<>(List.of("foo", "bar")); strings.add("baz");

또는 Java 8 또는 이전 버전:

 List<String> strings = new ArrayList<>(asList("foo", "bar")); strings.add("baz");

또는 Stream 사용:

 import static java.util.stream.Collectors.toCollection; List<String> strings = Stream.of("foo", "bar") .collect(toCollection(ArrayList::new)); strings.add("baz");

List 에 수집하는 대신 Stream 직접 사용하는 것이 좋습니다.

* ArrayList 가 필요하지 않을 것입니다. JEP 269 인용:

미리 정의된 값 집합으로 변경 가능한 컬렉션 인스턴스를 초기화하는 작은 사용 사례 집합이 있습니다. 일반적으로 미리 정의된 값을 변경할 수 없는 컬렉션에 넣은 다음 복사 생성자를 통해 변경 가능한 컬렉션을 초기화하는 것이 좋습니다.

(강조 내)


Community Wiki

크기 1의 간단한 목록이 필요한 경우:

 List<String> strings = new ArrayList<String>(Collections.singletonList("A"));

여러 개체 목록이 필요한 경우:

 List<String> strings = new ArrayList<String>(); Collections.addAll(strings,"A","B","C","D");

Randyaa

구아바 를 사용하면 다음과 같이 작성할 수 있습니다.

 ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");

Guava에는 다른 유용한 정적 생성자가 있습니다. 여기에서 그들에 대해 읽을 수 있습니다.


Paweł Adamski

JEP 269: Convenience Factory Methods for Collections 에서 제안한 바와 같이 이상을 사용하면 이제 다음과 같은 컬렉션 리터럴을 사용하여 이를 달성할 수 있습니다.

 List<String> list = List.of("A", "B", "C"); Set<String> set = Set.of("A", "B", "C");

Map 에도 유사한 접근 방식이 적용됩니다.

 Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

@coobird가 언급한 Collection Literals 제안 과 유사합니다. JEP에서도 자세히 설명 -


대안

언어 변경은 여러 번 고려되었지만 거부되었습니다.

프로젝트 코인 제안, 2009년 3월 29일

프로젝트 코인 제안, 2009년 3월 30일

2014년 1월-3월, lambda-dev에 대한 JEP 186 토론

언어 제안은 이 메시지에 요약된 대로 라이브러리 기반 제안보다 우선적으로 제외되었습니다.

관련: Java 9의 컬렉션에 대한 오버로드된 Convenience Factory 메서드의 요점은 무엇입니까?


Naman

컬렉션 리터럴은 Java 8에 포함되지 않았지만 Stream API를 사용하여 다소 긴 한 줄로 목록을 초기화할 수 있습니다.

 List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());

ListArrayList 인지 확인해야 하는 경우:

 ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));

Mark

import com.google.common.collect.ImmutableList; .... List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");

George

팩토리 메소드를 생성할 수 있습니다:

 public static ArrayList<String> createArrayList(String ... elements) { ArrayList<String> list = new ArrayList<String>(); for (String element : elements) { list.add(element); } return list; } .... ArrayList<String> places = createArrayList( "São Paulo", "Rio de Janeiro", "Brasília");

그러나 첫 번째 리팩토링보다 훨씬 낫지 않습니다.

유연성을 높이기 위해 다음과 같이 일반화할 수 있습니다.

 public static <T> ArrayList<T> createArrayList(T ... elements) { ArrayList<T> list = new ArrayList<T>(); for (T element : elements) { list.add(element); } return list; }

Jordão

Java 9에서는 한 줄로 ArrayList 를 쉽게 초기화할 수 있습니다.

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

또는

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

Java 9의 이 새로운 접근 방식은 이전 방식에 비해 많은 이점이 있습니다.

  1. 공간 효율성
  2. 불변성
  3. 스레드 안전

자세한 내용은 이 게시물 참조 -> List.of와 Arrays.asList의 차이점은 무엇입니까?


Mohit Tyagi

이를 수행하는 가장 간단한 방법은 다음과 같습니다.

 Double array[] = { 1.0, 2.0, 3.0}; List<Double> list = Arrays.asList(array);

Richard B

아래 코드를 다음과 같이 사용하면 됩니다.

 List<String> list = new ArrayList<String>() {{ add("A"); add("B"); add("C"); }};

user2801794

Eclipse Collections 를 사용하여 다음을 작성할 수 있습니다.

 List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");

또한 유형과 해당 유형이 변경 가능 또는 불변인지에 대해 더 구체적으로 설명할 수 있습니다.

 MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata"); ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");

세트 및 가방에서도 동일한 작업을 수행할 수 있습니다.

 Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata"); MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata"); ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata"); Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata"); MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata"); ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");

참고: 저는 Eclipse Collections의 커미터입니다.


Donald Raab

다른 방법은 다음과 같습니다.

 List<String> values = Stream.of("One", "Two").collect(Collectors.toList());

Henok T

(댓글이어야 하지만 너무 길어서 새로운 답변입니다.) 다른 사람들이 언급했듯이 Arrays.asList 메서드는 크기가 고정되어 있지만 이것이 유일한 문제는 아닙니다. 또한 상속을 잘 처리하지 않습니다. 예를 들어 다음이 있다고 가정합니다.

 class A{} class B extends A{} public List<A> getAList(){ return Arrays.asList(new B()); }

컴파일러 오류에 위의 결과 때문 List<B> (Arrays.asList에 의해 반환되는 것입니다)의 서브 클래스가 아닌 List<A> 당신이에 B 형의 객체를 추가 할 수 있지만, List<A> 객체 . 이 문제를 해결하려면 다음과 같이 해야 합니다.

 new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))

이것은 아마도 이것을 하는 가장 좋은 방법일 것입니다. 무제한 목록이 필요하거나 상속을 사용해야 하는 경우.


user439407

다음 명령문을 사용할 수 있습니다.

코드 조각:

 String [] arr = {"Sharlock", "Homes", "Watson"}; List<String> names = Arrays.asList(arr);

Community Wiki

톰이 말했듯이 :

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

그러나 ArrayList를 원한다고 불평했으므로 먼저 ArrayList가 List의 하위 클래스라는 것을 알아야 하며 다음 줄을 추가하기만 하면 됩니다.

 ArrayList<String> myPlaces = new ArrayList(places);

그러나 그것은 '성능'에 대해 불평하게 만들 수 있습니다.

이 경우 나에게 의미가 없습니다. 왜 목록이 미리 정의되어 있기 때문에 배열로 정의되지 않았습니다(초기화 시 크기가 알려져 있기 때문에). 그리고 그것이 당신을 위한 옵션이라면:

 String[] places = {"Buenos Aires", "Córdoba", "La Plata"};

사소한 성능 차이가 신경쓰이지 않는 경우 배열을 ArrayList에 매우 간단하게 복사할 수도 있습니다.

 ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));

알겠습니다. 하지만 앞으로는 장소 이름뿐만 아니라 국가 코드도 필요합니다. 이것이 런타임 동안 절대 변경되지 않는 미리 정의된 목록이라고 가정하면, 나중에 목록을 변경해야 하는 경우 다시 컴파일해야 enum

 enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}

될 것입니다:

 enum Places { BUENOS_AIRES("Buenos Aires",123), CORDOBA("Córdoba",456), LA_PLATA("La Plata",789); String name; int code; Places(String name, int code) { this.name=name; this.code=code; } }

열거형에는 선언된 순서대로 열거형의 모든 값을 포함하는 배열을 반환하는 values

 for (Places p:Places.values()) { System.out.printf("The place %s has code %d%n", p.name, p.code); }

이 경우 ArrayList가 필요하지 않을 것 같습니다.

PS Randya는 정적 유틸리티 메서드 Collections.addAll을 사용하여 또 다른 좋은 방법을 보여주었습니다 .


Ozzy

Java 9에는 변경할 수 없는 목록을 만드는 다음과 같은 방법이 있습니다.

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

필요한 경우 변경 가능한 목록을 생성하도록 쉽게 조정됩니다.

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

SetMap 대해 유사한 방법을 사용할 수 있습니다.


user85421

List<String> names = Arrays.asList("2","@2234","21","11");

Ran Adler

예, 배열의 도움으로 배열 목록을 한 줄로 초기화할 수 있습니다.

 List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");

Akash Manngroliya

당신은 사용할 수 있습니다 StickyList 에서 Cactoos :

 List<String> names = new StickyList<>( "Scott Fitzgerald", "Fyodor Dostoyevsky" );

yegor256

다음 코드 라인으로 시도하십시오.

 Collections.singletonList(provider)

Ant20

자바에서는 할 수 없다

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

지적했듯이 이중 중괄호 초기화를 수행해야 합니다.

 List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};

@SuppressWarnings("serial") 주석을 추가하거나 성가신 직렬 UUID를 생성하도록 강제할 수 있습니다. 또한 대부분의 코드 포맷터는 이를 여러 문장/줄로 풀어줍니다.

또는 할 수 있습니다

 List<String> places = Arrays.asList(new String[] {"x", "y" });

@SuppressWarnings("unchecked") 원할 수 있습니다.

또한 javadoc에 따르면 다음을 수행할 수 있어야 합니다.

 List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

그러나 JDK 1.6으로 컴파일할 수 없습니다.


Dawg

Arrays.asList 사용하기 Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); 맞다. 그러나 인수가 0이거나 하나의 인수만 있는 Arrays.asList() 모든 호출은 일부 메모리를 절약 Collections.singletonList() 또는 Collections.emptyList()

Collections.singletonList() 반환된 목록은 변경할 수 없는 반면 Arrays.asList() 반환된 목록은 set() 메서드 호출을 허용합니다. 드물게 코드가 손상될 수 있습니다.


aKilleR

Collections.singletonList(messageBody)

하나의 항목 목록이 필요하다면!

컬렉션 은 java.util 패키지에서 가져옵니다.


ViliusK

가장 좋은 방법:

 package main_package; import java.util.ArrayList; public class Stackkkk { public static void main(String[] args) { ArrayList<Object> list = new ArrayList<Object>(); add(list, "1", "2", "3", "4", "5", "6"); System.out.println("I added " + list.size() + " element in one line"); } public static void add(ArrayList<Object> list,Object...objects){ for(Object object:objects) list.add(object); } }

원하는 만큼 요소를 가질 수 있는 함수를 만들고 호출하여 한 줄에 추가하기만 하면 됩니다.


Charif DZ

다음은 AbacusUtil의 코드입니다.

 // ArrayList List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata"); // HashSet Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata"); // HashMap Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3); // Or for Immutable List/Set/Map ImmutableList.of("Buenos Aires", "Córdoba", "La Plata"); ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata"); ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3); // The most efficient way, which is similar with Arrays.asList(...) in JDK. // but returns a flexible-size list backed by the specified array. List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");

선언: 저는 AbacusUtil의 개발자입니다.


user_3380739

나에게 Arrays.asList()는 가장 좋고 편리한 것입니다. 저는 항상 그렇게 초기화하는 것을 좋아합니다. Java Collections의 초보자라면 ArrayList 초기화를 참조하시기 바랍니다.


Manoj Kumar

왜 이것을 하는 간단한 유틸리티 함수를 만들지 않습니까?

 static <A> ArrayList<A> ll(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; }

" ll "은 "리터럴 목록"을 나타냅니다.

 ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");

Stefan Reich

흥미롭게도 다른 오버로드된 Stream::collect 메서드가 포함된 단일 라이너는 나열되지 않습니다.

 ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );

Kaplan

출처 : http:www.stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line

반응형