varargs 메서드 매개 변수에 ArrayList를 전달하는 방법은 무엇입니까?
기본적으로 위치의 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
가장 쉬운 방법은 무엇입니까? 지금 당장 똑바로 생각하지 않는 것 같습니다.
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()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
이 게시물은 여기 기사로 다시 작성되었습니다 .
자바 8 :
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
구아바를 사용하여 허용되는 답변의 짧은 버전 :
.getMap(Iterables.toArray(locations, WorldLocation.class));
toArray를 정적으로 가져 와서 더 짧아 질 수 있습니다.
import static com.google.common.collect.toArray;
// ...
.getMap(toArray(locations, WorldLocation.class));
당신은 할 수 있습니다 : getMap(locations.toArray(new WorldLocation[locations.size()]));
또는 getMap(locations.toArray(new WorldLocation[0]));
또는getMap(new WorldLocation[locations.size()]);
ide 경고를 제거하려면 @SuppressWarnings ( "checked")가 필요합니다.
참고 URL : https://stackoverflow.com/questions/9863742/how-to-pass-an-arraylist-to-a-varargs-method-parameter
'Programing' 카테고리의 다른 글
Windows의 로컬 파일 시스템에서 GIT 복제 저장소 (0) | 2020.05.09 |
---|---|
DLL 파일이란 무엇이며 어떻게 작동합니까? (0) | 2020.05.09 |
UIView에 Perspective 변환을 어떻게 적용합니까? (0) | 2020.05.09 |
좋은 비속어 필터를 어떻게 구현합니까? (0) | 2020.05.09 |
GMail, Yahoo 또는 Hotmail을 사용하여 Java 애플리케이션으로 이메일을 보내려면 어떻게해야합니까? (0) | 2020.05.09 |