Java学习

数组

数组的初始化

1
2
3
4
5
6
7
 //方式一
int[] anArray = new int[10];
//方式二
int anOtherArray[] = new int[10];

//二维数组
int[][] array = new int[10][10];

数组的排序

1
2
3
//方式一,使用Arrays提供的sort()方法
int[] array = new int[] {1,4,5,2,3};
Arrays.sort(array);

数组的查找

1
2
int[] array = new int[] {1,2,3,4,5};
Arrays.binarySearch(array,2);

数组的复制

1
2
3
4
5
6
7
8
9
int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
//构建合并数组
int[] newArray = new int[array1.length+array2.length];
//复制两个数组到合并数组
System.arraycopy(array1,0,newArray,0,array1.length);
System.arraycopy(array2,0,newArray,array1.length,array2.length);
//输出合并后的数组
System.out.println(Arrays.toString(newArray));

打印数组

stream流打印

1
2
3
4
String [] cmowers = {"沉默","王二","一枚有趣的程序员"};
Arrays.asList(cmowers).stream().forEach(s -> System.out.println(s));
Stream.of(cmowers).forEach(System.out::println);
Arrays.stream(cmowers).forEach(System.out::println);

for循环打印

Arrays工具类打印(推荐)

1
2
3
4
5
6
//一维数组的打印
String[] cmowers = {"沉默","王二","一枚有趣的程序员"};
System.out.println(Arrays.toString(cmowers));
//二维数组的打印
String[][] deepArray = new String[][] {{"沉默", "王二"}, {"一枚有趣的程序员"}};
System.out.println(Arrays.deepToString(deepArray));