Java数组创建机制 数组类型比较 数组clone 数组迭代拷贝排序

2017-04-06 21:47:00
admin
原创 1755
摘要:Java数组创建机制 数组类型比较 数组clone 数组迭代拷贝排序

一、Java数组创建机制

数组length属性返回类型是int。


代码编译:char[] array = {'a', 'b'}

0: iconst_2
1: newarray       char
3: dup
4: iconst_0
5: bipush        97
7: castore
8: dup
9: iconst_1
10: bipush        98
12: castore
13: astore_0


二、数组类型比较

public static void testArrayEquals() {

System.out.println(new int[4].getClass());
System.out.println(new int[4][4].getClass());
System.out.println(new int[4].getClass() == new int[8].getClass());
System.out.println(new int[4][4].getClass() == new int[8][8].getClass());
}


输出:

class [I
class [[I
true
true


三、数组clone

public static void testClone() {
byte[] src = {1,2,3,4};
byte[] dst = src.clone();
System.out.println(src);
System.out.println(Arrays.toString(src));
System.out.println(dst);
System.out.println(Arrays.toString(dst));
}


输出:

[B@15db9742
[1, 2, 3, 4]
[B@6d06d69c
[1, 2, 3, 4]


四、数组迭代拷贝排序

数组迭代:

1、for循环迭代支持静态数组和Iterable接口,动态数组都有实现Iterable接口,所以动态数组可以迭代

2、静态数组for迭代会查询数组长度,动态数组for迭代会查询数组迭代器,所以数组为空抛出异常;

3、Iterator和Enumeration都是迭代器,Iterator包含Enumeration的功能,优先考虑实现Iterator;


数组拷贝:

System.arraycopy,拷贝数组内容到另外一个数组;

Arrays.copyOf(T[] original,int newLength),新建数组并且复制内容到新数组,复制过程可能截断或者填充null;

Arrays.copyOf(U[] original,int newLength,Class<? extends T[]> newType),功能同上并且可以指定新数组类型;

ArrayList.toArray(),实际上是调用Arrays.copyOf,只能返回Object数组;

ArrayList.toArray(T[] a),如果参数长度足够则调用System.arraycopy,如果参数长度不足则调用Arrays.copyOf


数组排序:

Arrays.sort(Object[] a),数组排序,对象需要实现Comparator接口,String默认实现了该接口;
Collections.sort(List<T> list),动态数组排序,对象需要实现Comparator接口,String默认实现了该接口

发表评论
评论通过审核之后才会显示。