java基础复习(数组)

  • 数组声明:
int[] a, b;  // Both a and b are arrays of type int
int c[], d;  // WARNING: c is an array, but d is just a regular int
  • 数组初始化initialize:

An array initializer creates an array and provides initial values for all its components.

//初始化的值为:
For references (anything that holds an object) that is null.
For int/short/byte/long that is a 0.
For float/double that is a 0.0
For booleans that is a false.
For char that is the null character '\u0000' (whose decimal equivalent is 0).
  • 一句话声明、初始化数组
//注意,不能分开写
int[] array1 = {1, 2, 3, 4, 5, 6, ,7, 8}; - working

//错误示范
int[] array1;
array1 = {1, 1, 1, 1, 2, 5, ,7, 8}; - NOT working

//应改成
array = new int[] {1, 1, 2, 3, 5, 8};

数组一旦创建,大小就确定了
可以用arr.length 获得数组长度

  • 增强型for循环 foreach
for (elementType value: arrayRefVar) {
  // 语句
 }

需要注意的问题:
在foreach循环中不要去删除元素!
正确的写法应该是:

List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}
//!!
//Note that the code calls Iterator.remove, not List.remove.

若想在循环中删除元素,则应该使用iterator,因为foreach是语法糖,内部是使用迭代器实现的,但对外隐藏了iterator的细节。我们并不知道一个collection内部实现,所以在foreach中删除元素,可能导致意想不到的错误
It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can’t access it to call Iterator.remove.
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

  • 数组的复制

1、通过循环语句实现
2、System.arraycopy

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );

3、Arrays.copyOf(比clone快)

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);

4、clone

int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();
  • 二维数组

二维数组的创建
1、int[][] multi = new int[5][10];(是2的简便写法)
2、

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

//以上等价于
int[][] multi = new int[][]{
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

二维数组的维度
行:arr.length
列:arr[i].length

int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception

猜你喜欢

转载自blog.csdn.net/normol/article/details/78879418