varargs 메서드 매개 변수에 ArrayList를 전달하는 방법은 무엇입니까?


236

기본적으로 위치의 ArrayList가 있습니다.

ArrayList<WorldLocation> locations = new ArrayList<WorldLocation>();

이 아래에서 나는 다음과 같은 방법을 호출

.getMap();

getMap () 메소드의 매개 변수는 다음과 같습니다.

getMap(WorldLocation... locations)

내가 겪고있는 문제는 그 방법에 대한 전체 목록을 전달하는 방법을 잘 모르겠다 locations는 것입니다.

난 노력 했어

.getMap(locations.toArray())

그러나 getMap은 Objects []를 허용하지 않으므로이를 허용하지 않습니다.

이제 내가 사용하면

.getMap(locations.get(0));

그것은 완벽하게 작동하지만 ... 어쨌든 모든 위치를 통과해야합니다 ... 물론 계속 추가 할 수는 locations.get(1), locations.get(2)있지만 배열의 크기는 다릅니다. 나는 단지 전체 개념에 익숙하지 않다ArrayList

가장 쉬운 방법은 무엇입니까? 나는 지금 똑바로 생각하지 않는 것처럼 느낍니다.


답변:


340

소스 기사 : 리스트를 vararg 메소드에 인수로 전달


toArray(T[] arr)방법을 사용하십시오 .

.getMap(locations.toArray(new WorldLocation[locations.size()]))

( toArray(new WorldLocation[0])또한 작동하지만 아무 이유없이 길이가 0 인 배열을 할당합니다.)


다음은 완전한 예입니다.

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("wordld");

    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

1
이 작업은 메모리 및 속도 측면에서 비용이 얼마나 듭니까?
— mindreader

추가 템플릿이 포함 된 경우 경고없이 작동하지 않습니다. 예를 들어 someMethod(someList.toArray(new ArrayList<Something>[someList.size()]))함수가 몇 줄보다 길면 매우 성가신 경고를 줄 것입니다 (전체 함수에 대해 함수를 억제하거나 추가 단계에서 배열을 작성하고 변수에 대한 경고를 억제해야하기 때문에) 저장합니다.
— Qw3ry

23
분명히 가장 빠른 방법은 배열의 크기가 아닌 크기를 0으로 지정하는 것입니다. 즉, 컴파일 타임 상수를 통해 최적화 된 방법을 사용할 수 있기 때문입니다. shipilev.net/blog/2016/arrays-wisdom-ancients
— geg

2
@JoshM. 자바에는 많은 것들이 필요합니다. ;) 또한 (C # 배경에서 오는) 색인 연산자가 누락되었습니다. 사전 작업은 Java에서 HashMaps를 사용하는 것보다 C #에서 훨씬 매끄 럽습니다.
— Per Lundberg

@PerLundberg-완전히 동의합니다. 또한 현재 Java를 사용하는 C # 개발자입니다. 아마도 10/11이 더 나을 것입니다. :-P
— Josh M.

42

자바 8 :

List<WorldLocation> locations = new ArrayList<>();

.getMap(locations.stream().toArray(WorldLocation[]::new));

2
이것은 자바 부두이지만, 더 나은 자바 (8) 부두입니다 .. 감사합니다!
— granadaCoder

locations.toArray(WorldLocations[]::new)또한 자바 11 이후로 작동하는 것 같습니다 (없이 .stream())
— Eran Medan

12

구아바를 사용하여 허용되는 답변의 짧은 버전 :

.getMap(Iterables.toArray(locations, WorldLocation.class));

toArray를 정적으로 가져 와서 더 짧아 질 수 있습니다.

import static com.google.common.collect.toArray;
// ...

    .getMap(toArray(locations, WorldLocation.class));

1

넌 할 수있어:

getMap(locations.toArray(new WorldLocation[locations.size()]));

또는

getMap(locations.toArray(new WorldLocation[0]));

또는

getMap(new WorldLocation[locations.size()]);

@SuppressWarnings("unchecked") ide 경고를 제거하는 데 필요합니다.


1
두 번째 솔루션이 더 좋습니다!
— gaurav
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.