ArrayList를 varargs 메서드 파라미터에 전달하려면 어떻게 해야 합니까?
기본적으로 다음과 같은 장소의 Array List가 있습니다.
ArrayList<WorldLocation> locations = new ArrayList<WorldLocation>();
아래에서는 다음 방법을 부릅니다.
.getMap();
getMap() 메서드의 파라미터는 다음과 같습니다.
getMap(WorldLocation... locations)
내가 안고 있는 문제는 어떻게 전체 목록을 통과해야 할지 모르겠다는 것이다.locations
그 방법을 사용합니다.
해봤어요
.getMap(locations.toArray())
단, getMap은 오브젝트[]를 받아들이지 않기 때문에 그것을 받아들이지 않습니다.
이제 내가 사용한다면
.getMap(locations.get(0));
완벽하게 작동될 거야하지만 어떻게든 모든 곳을 통과해야 해요물론 계속 추가할 수 있습니다.locations.get(1), locations.get(2)
어레이의 사이즈는 다릅니다.난 단지 이 모든 개념에 익숙하지 않을 뿐이야ArrayList
가장 쉬운 방법은 무엇일까요?내가 지금 제대로 생각을 못하고 있는 것 같아.
소스 기사: 목록을 인수로 vararg 메서드에 전달
방법을 사용합니다.
.getMap(locations.toArray(new WorldLocation[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("world");
method(strs.toArray(new String[0]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
Java 8의 경우:
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
Guava를 사용한 승인된 답변의 단축 버전:
.getMap(Iterables.toArray(locations, WorldLocation.class));
Array에 정적으로 Import하면 더 단축할 수 있습니다.
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 경고를 삭제하려면 이 필요합니다.
여기에서는 해결되었다고 표시되어 있습니다만, KOTLIN RESOLUTION
fun log(properties: Map<String, Any>) {
val propertyPairsList = properties.map { Pair(it.key, it.value) }
val bundle = bundleOf(*propertyPairsList.toTypedArray())
}
bundle Of에 vararg 파라미터가 있습니다.
언급URL : https://stackoverflow.com/questions/9863742/how-to-pass-an-arraylist-to-a-varargs-method-parameter
'programing' 카테고리의 다른 글
iframe과 상위 사이트 간의 통신 방법 (0) | 2022.11.08 |
---|---|
.lib가 스태틱인지 Import인지 확인합니다. (0) | 2022.11.08 |
Jaxb, 클래스에 동일한 이름의 속성이 두 개 있습니다. (0) | 2022.11.08 |
후행 슬래시 없이 문자열 반환 (0) | 2022.11.08 |
java 파일 intellij 아이디어로 디컴파일하는 방법 (0) | 2022.11.08 |