기본적으로 위치의 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
가장 쉬운 방법은 무엇입니까? 나는 지금 똑바로 생각하지 않는 것처럼 느낍니다.
답변
소스 기사 : 리스트를 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()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
답변
자바 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()]);
@SuppressWarnings("unchecked")
ide 경고를 제거하는 데 필요합니다.
답변
