IT이야기

한 줄에 배열 목록 초기화

cyworld 2022. 4. 19. 21:40
반응형

한 줄에 배열 목록 초기화

나는 테스트 목적을 위한 옵션 목록을 만들고 싶었다.처음에는 이렇게 했다.

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 하나 - 배열목록은 하나다.

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"));

사실, 아마도 초기화하는 가장 좋은 방법은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인스턴스 이니셜라이저가 있고, 그 클래스는 단지 하나의 대상을 창조하기 위해 만들어지는 것인데, 그것은 내게는 약간 과잉 살상처럼 보인다.

프로젝트 코인에 대한 콜렉션 리터럴즈 제안이 받아들여졌더라면 좋았을 텐데(자바 7에서 도입될 예정이었지만, 자바 8의 일부도 될 것 같지는 않다).

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

불행히도 여기선 도움이 안 될 겁니다 불변의 법칙을List…이라기보다는ArrayList그리고 더 나아가서는, 만약 그렇게 된다면, 아직 이용할 수 없다.

간단한 대답

Java 9 이상:

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

이것은 당신에게 불변의 법칙을 줄 것이다. List그래서 그것은 바뀔 수 없다.
대부분의 경우 미리 채울 때 원하는 것이 바로 그것이다.

Java 8 이전 버전:

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

이것은 당신에게 a를 얻을 수 있을 것이다.List* 길이를 변경할 수 없도록 배열에 의해 지원됨.
하지만 당신은 전화할 수 있다.List.set(...)그래서 여전히 변이할 수 있어

* Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList,
which is a different class from java.util.ArrayList, even though their simple names are the same.

정적 가져오기

자바 8을 만들 수 있다.Arrays.asList정적 가져오기를 사용하여 더 짧은 시간:

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

어떤 현대* IDE라도 이것을 제안하고 할 것이다.

정적으로 가져오지 마십시오.List.of정정당당하게 처리하다.of헷갈리니까.

* For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...

사용.Streams

하필이면 하하면...List?
8 에서는 자바 할 수 .Stream보다 유연한 방법:

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

너는 연결 할 수 있다.Streams:

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

또는 당신은 a로부터 갈 수 있다.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.

특별히 필요한 경우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");

하지만 다시 말하지만, 그냥 그 제품을 사용하는 것이 더 낫다.Stream에 직접 수집하는 것이 직접는이다.List.

*You probably don't need specifically an ArrayList. To quote JEP 269:

사전 정의된 값 집합으로 돌연변이 수집 인스턴스를 초기화하는 소수의 사용 사례가 있다.일반적으로 이러한 사전 정의된 값을 불변의 집합에 넣은 다음, 복사 생성자를 통해 돌연변이 수집을 초기화하는 것이 바람직하다.

(내 것)

구현이 아닌 인터페이스에 프로그램 적용

리스트를 리스트로 선언했다고 하셨잖아요.ArrayList코드에서, 하지만 당신은 단지 당신이 어떤 멤버를 사용하는 경우에만 그렇게 해야 한다.ArrayList 것은List.

네가 하고 있지 않을 가능성이 가장 높다.

일반적으로 사용할 가장 일반적인 인터페이스로 변수를 선언하십시오(예:Iterable Collection또는List )으로한다.ArrayList LinkedList또는Arrays.asList()).

그렇지 않으면 코드를 특정 유형으로 제한하게 되고, 원할 때 변경하기가 더 어려워질 것이다.

예를 들어, 만약 여러분이ArrayList완전히void method(...):

// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) { 
    for (String s : strings) { ... } 
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need random access, .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

또 다른 예는 항상 변수 a를 선언하는 것이다.InputStream보통은 a이긴 하지만FileInputStream또는 aBufferedInputStream왜냐하면 언젠가는 당신이나 다른 누군가가 다른 종류의 것을 사용하기를 원할 것이기 때문이다.InputStream.

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

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

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

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

Guava를 사용하여 다음과 같이 쓸 수 있다.

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

과바에는 다른 유용한 정적 생성자도 있다.당신은 여기서 그것들에 대해 읽을 수 있다.

JEP 269: 수집을 위한 편의 공장 방법에서 제안한 바와 같이, 이상의 경우, 이는 현재 수집 리터럴을 사용하여 달성될 수 있다.

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일

JEP 186 람다-dev에 대한 논의, 2014년 1월-3월

언어 제안은 이 메시지에 요약된 도서관 기반의 제안보다 우선하여 지정되었다.

관련:Java 9에서 수집을 위한 편의 공장 방법의 과부하 요점은 무엇인가?

수집 리터럴이 Java 8로 만들어지지는 않았지만 Stream API를 사용하여 하나의 긴 줄에 목록을 초기화할 수 있다.

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

다음 작업을 수행할 필요가 있는 경우List이다ArrayList:

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

....

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

공장 방법을 생성할 수 있는 경우:

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;
}

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의 차이점은?

아래 코드를 다음과 같이 간단히 사용하십시오.

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

이를 위한 가장 간단한 방법은 다음과 같다.

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

다른 방법은 다음과 같다.

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

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의 커밋자입니다.

(코멘트여야 하지만 너무 길어서 새로운 답변).다른 사람들이 언급했듯이, The는Arrays.asList방법은 고정된 크기지만, 그것만이 문제가 아니다.상속도 잘 처리하지 못한다.예를 들어 다음과 같이 가정해 보십시오.

class A{}
class B extends A{}

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

위와 같은 경우 컴파일러 오류가 발생하며,List<B>하는 것은 (Array.asListga는 는)의 .List<A>B 유형의 객체를 a에 추가할 수 있지만List<A>반대하다이 문제를 해결하려면 다음과 같은 조치를 취해야 한다.

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

이것이 아마도 이것을 하는 가장 좋은 방법일 것이다, esp. 만약 당신이 한없는 목록이 필요하거나 상속을 사용해야 한다면.

다음 문구를 사용할 수 있다.

코드 조각:

String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);

톰이 말한 것처럼:

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;
    }
}

Enum's has staticvalues예를 들어 다음과 같이 선언된 순서대로 열거값의 모든 값이 포함된 배열을 반환하는 방법:

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

그렇다면 어레이리스트는 필요 없을 것 같은데.

P.S. Randyaa는 정적 효용 방법 Collections.addAll을 사용하여 또 다른 멋진 방법을 시연했다.

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"));

유사한 방법을 사용할 수 있다.Set그리고Map.

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

어레이의 도움을 받아 한 줄에서 어레이 목록을 초기화할 수 있음

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

사용할 수 있다StickyList선인장 출신:

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

다음 코드 라인을 사용해 보십시오.

Collections.singletonList(provider)

사용. Arrays.asList("Buenos Aires", "Córdoba", "La Plata");맞는 말이야, 하지만 모든 전화는Arrays.asList()인수가 0이거나 단 하나의 인수가 호출로 대체될 수 있음Collections.singletonList()또는Collections.emptyList()기억력을 좀 살릴 수 있을 거야

참고: 반환된 목록Collections.singletonList()리스트가 반환되는 동안 불변함Arrays.asList()setcuit 메소드를 호출할 수 있다.이것은 드문 경우로 코드를 어길 수 있다.

자바에서는 할 수 없다.

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").

또한 자바독에 따르면 다음과 같이 할 수 있어야 한다.

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

하지만 나는 그것을 JDK 1.6과 컴파일 할 수 없다.

Collections.singletonList(messageBody)

가지 항목의 목록이 필요하다면!

컬렉션java.util 패키지에서 제공된다.

가장 좋은 방법:

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);
    }
}

원하는 만큼의 요소를 가질 수 있는 함수를 만들고 한 줄에 추가하기 위해 호출하면 된다.

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");

선언: 나는 아바쿠스유틸의 개발자다.

흥미롭게도 다른 한 여객기가 과부하된 것은 아니다. Stream::collect 메소드가 나열되다

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

나에게 있어 Arrays.asList()는 가장 좋고 편리한 것이다.나는 항상 그런 식으로 초기화하는 것을 좋아한다.Java Collection에 초보자라면 ArrayList 초기화를 참고해 주길 바란다.

이렇게 하는 간단한 유틸리티 기능을 만드는 것은 어떨까?

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

"ll는 "filency list"를 한다.

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

참조URL: https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line

반응형