数组
来源:互联网 发布:windows 7旗舰版密钥 编辑:程序博客网 时间:2024/05/21 22:28
数组的声明由几种方式:
1,String []a = new String[length];
a[0]=?;.......通过数组下标赋值
2,new的时间就初始化:
String []a = new String[]{?,?...};
3.不用new直接赋值:
String []a = {?,?....}
遍历数组的方法
一,for
- for(int i = 0; i < arr.length; i++){
- for(int j = 0; j < arr[i].length; j++){
- System.out.print(arr[i][j]);
- }
- int arr[][] = new int[][]{{4,3},{1,5}};
- //foreach语句遍历二维数组。
- System.out.println("数组中的元素是:");
- for(int x[]:arr){ //外层遍历得到一维数组
- for(int e:x){ //内层遍历得到数组元素
- System.out.print(e);
- }
- int arr[][] = new int[][]{{9,8},{7,6,5}};
- for(int i = 0; i < arr.length; i++){//循环得到一维数组
- System.out.println(Arrays.toString(arr[i]));//将一维数组转化为字符串输出
- }
数组常用函数
(1)输出一个数组
int[] arr = { 1, 2, 3, 4, 5 }; String arrString = Arrays.toString(arr);system.out.println(arrString);
结果:[1, 2, 3, 4, 5]
(2) 检查一个数组是否包含某值
String[] arr= { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(arr).contains("a"); System.out.println(b); // true
Arrays.asList()将一个数组转化为一个List对象,这个方法会返回一个ArrayList类型
(3)连接两个数组
1 int[] arr1 = { 1, 2, 3, 4, 5 }; 2 int[] arr2= { 6, 7, 8, 9, 10 }; 3 int[] combArr = ArrayUtils.addAll(arr1 , arr2);(4)逆向输出一个数组
int[] arr= { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray));java代码实现
(5)移除数组中的元素int[] arr = { 1, 2, 3, 4, 5 };int[] revArr = new int[arr.length]; for(int i = 0; i < arr.length; i++){ revArr[i] = arr[arr.length - i -1]; } System.out.println(Arrays.toString(revArr));
int[] arr= { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array System.out.println(Arrays.toString(removed))(6)System.arraycopy方法复制数组
复制指定源数组src到目标数组dest。复制从src的srcPos索引开始,复制的个数是length,复制到dest的索引从destPos开始。
- public static native void arraycopy(Object src, int srcPos,
- Object dest, int destPos,
- int length);
(8)arrays.copyof()复制
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1,arr1.length);
arr1要复制的数组,复制的长度ArrayUtils数组操作
0 0