2013-10-12 3 views
3
import java.util.Arrays; 
import java.util.List; 
import java.util.ArrayList; 

public class arraysAsList { 


    public static void main(String[] args) { 

     String [] arrayA = {"Box","Sun","Clock","Phone"}; 
     Integer [] arrayB = {21,27,24,7}; 

     List listStructureA = new ArrayList(); 
     List listStructureB = new ArrayList(); 

     listStructureA = Arrays.asList(arrayA); 
     listStructureB = Arrays.asList(arrayB); 

     System.out.println("My first list : " + listStructureA); 
     System.out.println("Sun = " + listStructureA.get(1)); 
     System.out.println("My second list : " + listStructureB); 
     System.out.println("24 = " + listStructureB.get(2)); 

    } 

} 

int는 기본 유형이고 Integer는 클래스라는 것을 알고 있습니다. 하지만이 스크립트에서 Integer 대신 int를 사용하려고하면 'index out of bounds exception'오류가 발생합니다. int를 사용하여 배열을 작성하기 전에 int 배열과 Integer 배열의 차이점은 무엇입니까? 미리 감사드립니다.이 스크립트에서 int와 Integer의 차이점은 무엇입니까?

답변

7

Arrays.asList(T...)에는 varargs가 걸립니다. Integer[]을 전달하면 T 유형은 Integer으로 추정되며 Integer[]의 각 요소는 varargs의 다른 인수로 압축 해제됩니다. 당신이 int[]을 통과 그러나

, int가 대상이 아니므로, Tint[]로 추정된다. 따라서이 메서드에 전달되는 값은 int[] 인 단일 요소 배열입니다. 그래서, varargs의 수는 두 경우 모두 다릅니다. 따라서 색인 1에 액세스하면 int[]을 전달할 때 오류가 발생합니다.

그래서 한 줄에 - Integer[]은 객체에 대한 참조 배열이며, int[] 그 자체가 객체입니다.

int[] arr = {1, 2, 3}; 
Integer[] arr2 = {1, 2, 3}; 

test(arr); // passing `int[]`. length is 1 
test(arr2); // passing `Integer[]`. length is 3 
:

public static <T> void test(T... args) { 
    System.out.println(args.length); 
} 

그런 다음이 메소드를 호출

당신은이 방법으로, 간단한 테스트를 할 수있는

관련 문제