赞
踩
一、一维数组的创建方法:
方法一:
int[] array=new int[5]; //定义一个长度为5的整型数组
方法二:
int[] array={1,2,3,4,5} //也可以直接赋值
1、将数组转换为字符串:Arrays.toString()
- int[] array={1,2,3};
- System.out.println(array); // 输出为内存地址
- System.out.println(Arrays.toString(array)); // [1,2,3]
2、数组的填充:
2.1. 数组元素的填充: Arrays.fill(数组名,value)
- int[] array=new int[5];
- Arrays.fill(array,6);
- System.out.println(Arrays.toString(array)); // [6,6,6,6,6]
2.2. 数组片段填充:Arrays.fill(数组名,起始index,结束index,value)
- int[] array=new int[5];
- Arrays.fill(array,1,3,5);
- System.out.println(Arrays.toString(array)); // [0,5,5,5,0]
3、数组的排序:Arrays.sort(数组名)
- int[] array={8,15,6,9,-1,0,52,-5};
- Arrays.sort(array);
- System.out.println(Arrays.toString(array)); // [-5,-1,0,6,8,9,15,52]
4、二分法查找:Arrays.binarySearch(数组名,intkey),二分法查找的数组需是有序的。
- int[] array={-5,-1,0,6,8,9,15,50};
- int result=Arrays.binarySearch(array,8);
- System.out.println(result); // 4 , 若找到key则返回key的在数组中的index
-
-
- int result2=Arrays.binarySearch(array,12);
- System.out.println(result2); // -7 ,若没有找到Key,返回负值绝对值是在有序前提下的数据个数
5、数组相等的判定:
5.1.Arrays.equals(数组A,数组B):返回值为boolean值
- int[] a={8,15,6,9,-1,0,52,-5};
- int[] b={8,15,6,9,-1,0,52,-5};
- System.out.println(a==b); // false 比较的是数组在内存中的地址
- boolean result=Arrays.equals(a,b);
- System.out.println(result); // true
-
5.2.Arrays.compare(数组A,数组B):比较俩个数组中是否存在第一个不相等的元素,返回值为int值,不存在返回0,存在且第一个数组中不相等的元素比第二个数组中的元素大,返回1,反之返回-1
- int[] a={8,15,6,9,-1,0,52,-5};
- int[] b={8,15,6,9,-1,0,52,-5};
-
- int result=Arrays.compare(a,b);
- System.out.println(result); // 0
6、数组的复制、浅拷贝问题。
- int[] a={8,15,6,9,-1,0,52,-5};
- int[] b=a;
- System.out.println(Arrays.toString(a)); // [8,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)); // [8,15,6,9,-1,0,52,-5]
-
- b[0]=200;
-
- System.out.println(Arrays.toString(a)); // [200,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)); // [200,15,6,9,-1,0,52,-5]
6.1.Arrays.copyOf(数组名,int newLength):将数组的newLength个数组元素形成新数组并返回。
- int[] a={8,15,6,9,-1,0,52,-5};
- int[] b=Arrays.copyOf(a,a.length);
- System.out.println(Arrays.toString(a)) // [8,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)) // [8,15,6,9,-1,0,52,-5]
-
- b[0]=200;
-
- System.out.println(Arrays.toString(a)) // [8,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)) // [200,15,6,9,-1,0,52,-5]
6.2.使用数组的clone()方法对源数组进行克隆。
- int[] a={8,15,6,9,-1,0,52,-5};
- int[] b=a.clone();
- System.out.println(Arrays.toString(a)) // [8,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)) // [8,15,6,9,-1,0,52,-5]
-
- b[0]=200;
-
- System.out.println(Arrays.toString(a)) // [8,15,6,9,-1,0,52,-5]
- System.out.println(Arrays.toString(b)) // [200,15,6,9,-1,0,52,-5]
7、Array与ArrayList的转换:将Array转换为ArrayList:Arrays.asList()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。