天天看點

Arrays.asList contains int無效

int[] ints = {1,2,3,4};
		
		if(Arrays.asList(ints).contains(3)){
			System.out.println("true");
		}else{
			System.out.println("false");
		}
           

輸出false

從我了解角度講講這種現象

public static <T> List<T> asList(T... a) {
      return new ArrayList<>(a);
}
           

1、基本資料類型是無法泛型化的,也就是說 8 個基本類型是無法作為 asList 的參數的,為啥沒報錯呢,因為數組是對象。當成對象了。輸出ints可見  [[email protected] 

int[] ints = {1,2,3,4};
		
if(Arrays.asList(ints).contains(ints)){
	System.out.println("true");
}else{
	System.out.println("false");
}
           

輸出true

2、修改int[] 成 Integer[] ,再次contains(3),true。

asList 方法。Java将可變長參數當成數組對待。可以将一個數組或可變的參數個數傳遞給可變長參數。當用可變的參數個數調用方法時,Java會建立一個數組并把參數傳給它。

a本質就是一個數組,是以當對象類型數組直接可以傳給它