: 당신은 뭔가를 할 수 있습니다 정말 일반적이지 않은 것을 제외하고는이를 수행하는 메소드를 정의합니다. 복사 할 배열을 지정하거나 Object[]
을 사용해야합니다.
List<String> strList = new ArrayList<String>();
Object[] objArr = strList.toArray();
String[] strArr = strList.toArray(new String[strList.size()]);
나는 둘 중 누구도 원하지 않는 것으로 가정합니다. 불행히도 자바에서 배열을 일반적으로 만들 수 없기 때문에 원하는 것을 정확히 수행 할 방법이 없습니다. 방법으로 돌아 간다 :
이
public static <E> E[] toArray(List<E> list) {
E[] arr = new E[list.size()]; // doesn't compile
return list.toArray(arr);
}
E
이 erased 것을되는 문제는 그래서 컴파일 가능한 자바 코드가 아닙니다. 실행시에 이 존재하지 않아 new E
을 수행 할 수 없습니다.
그래서 당신이 얻을 수있는 가장 가까운이 같다 :
public static <E> E[] toArray(List<E> list, Class<E> e) {
@SuppressWarnings("unchecked")
final E[] arr = (E[])Array.newInstance(e, list.size());
return list.toArray(arr);
}
을하지만 정말 사용하기 더 편리하지 않습니다 :
List<String> strList = new ArrayList<String>();
String[] strArr = toArray(strList, String.class);
가 ArrayList
을 확장하는 또 다른 흥미로운 방법이있다 이 기능을 추가하십시오. 하지만 여전히 Class<E>
개체가 필요합니다. 이처럼 할 거라고 :
이
import java.util.Arraylist;
import java.util.Objects;
import java.lang.reflect.Array;
public class TypedList<E> extends ArrayList<E> {
private final Class<E> e;
public TypedList(Class<E> e) {
this.e = Objects.requireNonNull(e);
}
@Override
public E[] toArray() {
@SuppressWarnings("unchecked")
final E[] arr = (E[])Array.newInstance(e, size());
return toArray(arr);
}
}
이 당신이 처음에 Class<E>
를 지정하고 나중에 당신이, 예를 들어 인수와 toArray
를 호출 할 수 있습니다:
TypedList<String> strList = new TypedList<String>(String.class);
String[] strArray = strList.toArray();
나는 어레이를 일반적으로 사용하려고 시도하는 것을 피하려고한다. 그들은 이런 종류의 일에 좋지 않습니다.
가능한 복제본 : http://stackoverflow.com/questions/7969023/from-arraylist-to-array – csvan
복제본이 없으므로 검색을하고 그 중 하나를 보았습니다. – simonkaspers1
* "목록 반환 (도구 [])"* 이 부분을 분명히 해 주시겠습니까?'list (Tool []) '가 전달해야하는 것이 무엇인지 모르겠습니다. – Radiodef