简单的泛型方法

//===========================================================
//泛型方法
(main)
String[] names = {"小鹿","小羊","小牛","小河"};
printArray(names);

Integer[] ages = {14,22,33,55};
printArray(ages);

public static <T> void printArray(T[] arr){
//先判断数组是否为 null
if (arr != null){
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < arr.length; i++) {
if (i != arr.length-1){
sb.append(arr[i]).append(" ");//不应该sb.append(arr[i]+" ");
}else{
sb.append(arr[i]);
}
//以上两步可以成为一步骤 sb.append(arr[i]).append(i == arr.length - 1 ? "" :", ")

}
sb.append("]");
System.out.println(sb);

}else{
System.out.println(arr);
}

posted on 2022-03-22 17:36  我要当程序源  阅读(29)  评论(0)    收藏  举报

导航