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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值