一、foreach循环
这个是在1.5时加上的,现代计算机语言大多都有这个。例子如下:
public class Test1 { public static void main(String[] args) { String[] stringArray = {"linc","lincoln","james"}; for(String tmp:stringArray) { System.out.println(tmp); } } }二、数组的拷贝
System类下的arraycopy方法是不二选择。函数原型如下:
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)可以看到这个函数是一个native函数,函数主体是原生语言C\C++写成的,System类下的众多函数都如此,其中执行效率是一方面。
arraycopy共5个参数,分别是:
* @param src the source array.源数组 * @param srcPos starting position in the source array.源数组的起始位置 * @param dest the destination array.目标数组 * @param destPos starting position in the destination data.目标数组中的起始位置 * @param length the number of array elements to be copied 要拷贝的长度举例如下:
public class Test1 { public static void main(String[] args) { String[] stringArray = {"linc","lincoln","james"}; String[] destArray = {"andy","bobby","carl","david","edward","fred","gavin","howard","jack","ken","mark","neil","oscar","philip","robert","sam","tom","vincent","wesley"}; System.arraycopy(stringArray,0,destArray,9,3); for(String tmp:destArray) { System.out.println(tmp); } } }三、数组相关的异常
ArrayIndexOutOfBoundsException是我们项目中最常见的数组越界异常,它告诫我们使用数组时要小心。
比如上面的例子加上这一句就会引发异常:
String name = stringArray[4];
D:\workspace\Java\project261\array>java Test1 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Test1.main(Test1.java:8)