1、For each循环:
JDK5.0中提供的新特性For each循环的加入简化了集合的遍历。
1.1、语法:
1 2 3 4 5 for (type element : array){ … System.out.println(element); … }
1.2、For each循环的使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public static void main (String[] args) { List<String> arrayList = new ArrayList <String>(); arrayList.add("a" ); arrayList.add("b" ); arrayList.add("c" ); for (int i=0 ; i<arrayList.size(); i++){ System.out.println(arrayList.get(i)); } for (String element : arrayList){ System.out.println(element); } }
1.3、嵌套For each循环:
1 2 3 4 5 6 int [][] array = { {1 ,2 ,3 },{1 ,2 }};for (int [] row : array){ for (int element : row){ System.out.println(element); } }
1.4、三种循环遍历集合的列举:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 for (int i=0 ; i<arrayList.size(); i++){ System.out.println(arrayList.get(i)); } for (Iterator<String> iter = arrayList.iterator(); iter.hasNext();){ System.out.println(iter.next()); } for (String element : arrayList){ System.out.println(element); }
1.5、增强的for循环的缺点:
失去了索引信息,不能获取到索引值,只能这样获取:
1 2 3 4 5 6 int i = 0 ;for (String element : arrayList){ System.out.println(i + element); i++; }
因为增强的for循环会丢失下标信息,所以当遍历集合或数组时,如果需要方法集合或数组的下标,最好使用旧式的方式来实现循环或遍历。
2、自动装箱/拆箱(Autoboxing/unboxing):
自动装箱/拆箱打打方便类基本类型数据和它们包装类的使用。
自动装箱:把基本数据类型转换为包装类。
自动拆箱:把包转类型自动转换为基本数据类型。
2.1、自动装箱:
1 2 3 4 5 Collection<Integer> c = new ArrayList <Integer>(); c.add(1 ); c.add(2 ); c.add(3 );
2.2、自动拆箱:
1 2 3 4 for (Integer integer : c){ System.out.println(integer); }
2.3、Integer类相关的源代码:
2.3.1、valueOf方法:
1 2 3 4 5 6 public static Integer valueOf (int i) { if (i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128 ]; else return new Integer (i); }
这里对应-128~127的整数调用了IntegerCache.cache[i + 128];详细代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 private static class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128 ; int h = 127 ; if (integerCacheHighPropValue != null ) { int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127 ); h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; cache = new Integer [(high - low) + 1 ]; int j = low; for (int k = 0 ; k < cache.length; k++) cache[k] = new Integer (j++); } private IntegerCache () {} }
其主要的功能就是把-128~127的整数缓存起来,当要使用这些数字时,就从这些缓存中获取。
由此可知下面代码运行的结果为true:
1 2 3 Integer m = 127 ;Integer n = 127 ;System.out.println(m == n);
而下面的代码则为false:
1 2 3 Integer m = 128 ;Integer n = 128 ;System.out.println(m == n);
3、可变参数:
可变参数使得可以声明一个接受一个可变数目参数的方法。
可变参数必须是方法声明中的最后一个参数。
3.1、包含可变参数的函数:
1 2 3 4 5 6 7 public static int add (int ... arrays) { int sum = 0 ; for (Integer integer : arrays){ sum += integer; } return sum; }
可变参数部分相当于数组。
3.2、接收参数:
可以为多个参数或数组:
1 2 3 4 add(new int []{1 ,2 ,3 }); add(1 ,2 ,3 );
3.3、说明:
可变参数本质上是一个数组,声明了可变参数的方法,既可以传递离散的值,也可以传递一个数组对象。
可变参数必须作为方法参数的最后一个参数。