Arrays.copyOf () 방법 설명 - jdk1.8
14228 단어 java 원본 분석
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
보시다시피, 최종적으로 호출된 것은 시스템입니다.arraycopy () 방법, 이 방법의 사용에 관해서는 System을 볼 수 있습니다.arraycopy 상해
1. 방법의 의미
NewLength 및 original을 포함하는 T-유형의 배열을 반환합니다.length의 작은 값, 요소는original 그룹의 요소입니다. (0을 newLength와original.length의 작은 값으로 가져옵니다.)
말하자면, 이 방법은 바로 수조 원소의 상향 전환을 위한 것이고, 또 수조를 절단하는 것이다
2. (Object)newType == (Object)Object[].class
newType이 Object 배열인지 판단
3. 왜 (Object) 넣을까요?
==을 사용하여 그들의 메모리 주소를 비교하여 같은 유형인지 아닌지를 판단해야 하기 때문에 =을 사용하면 Object로 강제로 전환해야 한다. 그렇지 않으면 편집기가 통과하지 못하게 하고 비교할 수 없다.
public class SystemArrayCopy {
public static void main(String[] args) {
System.out.println(Object.class == Integer.class);
}
}
/*
:
Error:(37, 41) java: : java.lang.Class java.lang.Class
*/
추가(Object) 후
public class SystemArrayCopy {
public static void main(String[] args) {
System.out.println(Object.class == (Object)Integer.class);
}
}
/*
false
*/
4. newType.getComponentType()
public native Class<?> getComponentType();
로컬 방법, 그룹 내의 원소 형식을 되돌려줍니다. 그룹이 아닐 때null을 되돌려줍니다.
public class SystemArrayCopy {
public static void main(String[] args) {
String[] o = {"aa", "bb", "cc"};
System.out.println(o.getClass().getComponentType());
System.out.println(Object.class.getComponentType());
}
}
/*
class java.lang.String
null
*/
5. Array.newInstance(newType.getComponentType(), newLength)
newType과 같은 유형의 newLength 길이 배열을 만듭니다.
public static Object newInstance(Class<?> componentType, int length)
throws NegativeArraySizeException {
return newArray(componentType, length);
}
private static native Object newArray(Class<?> componentType, int length)
throws NegativeArraySizeException;
Array.newInstance에서 Array를 직접 호출합니다.newArray, newArray는 로컬 메서드로 VM에 의해 수행됨
새 Instance가 Object로 반환되고 배열로 변경됩니다.
public class SystemArrayCopy {
public static void main(String[] args) {
Object o = Array.newInstance(String.class, 10);
System.out.println(o.getClass());
System.out.println(String.class); //
}
}
/*
class [Ljava.lang.String;
class java.lang.String
*/
볼 수 있어, Array.Instance의 반환은 Object 형식이지만 실질적으로 String 그룹입니다. 예를 들어 String[] arr = (String[]) Array로 강제로 변환할 수 있습니다.newInstance(String.class, 10);
4. (T[]) new Object[new Length], 왜 Object[]는 T[]로 강제로 변환할 수 있습니까?
6. Object[]가 아닌 T[]로 강제로 전환한 이유는 무엇입니까?
왜냐하면 이 방법은 T[]로 돌아가는 것이기 때문에 이것은 방법이 쓴 본의이다
7. 역할