标签:
1. 声明一个数组
1 String[] arr1 = new String[5]; 2 String[] arr2 = {"a","b","c", "d", "e"}; 3 String[] arr3= new String[]{"a","b","c","d","e"};
2. 输出一个数组
1 int[] arr = { 1, 2, 3, 4, 5 }; 2 String arrString = Arrays.toString(arr); 3 4 // 直接输出,为内存地址 5 System.out.println(arr); 6 // [I@139a55 7 8 System.out.println(arrString ); 9 // [1, 2, 3, 4, 5]
3. 检查一个数组是否包含某值
1 String[] arr= { "a", "b", "c", "d", "e" }; 2 boolean b = Arrays.asList(arr).contains("a"); 3 System.out.println(b); 4 // true
4. 连接两个数组
1 //使用Apache Commons Lang library 2 3 1 int[] arr1 = { 1, 2, 3, 4, 5 }; 4 2 int[] arr2= { 6, 7, 8, 9, 10 }; 5 3 int[] combArr = ArrayUtils.addAll(arr1 , arr2);
// System.arraycopy()
1 static String[] concat(String[] a, String[] b) { 2 String[] c = new String[a.length + b.length]; 3 System.arraycopy(a, 0, c, 0, a.length); 4 System.arraycopy(b, 0, c, a.length, b.length); 5 return c; 6 }
1 //Arrays.copyOf() 2 3 public static int[] concat(int[] first, int[] second) { 4 int[] result = Arrays.copyOf(first, first.length + second.length); 5 System.arraycopy(second, 0, result, first.length, second.length); 6 return result; 7 }
5. 逆向输出一个数组
1 // Apache Commons Lang library 2 3 int[] arr= { 1, 2, 3, 4, 5 }; 4 ArrayUtils.reverse(intArray); 5 System.out.println(Arrays.toString(intArray)); 6 //[5, 4, 3, 2, 1]
1 int[] arr = { 1, 2, 3, 4, 5 }; 2 int[] revArr = new int[arr.length]; 3 for(int i = 0; i < arr.length; i++){ 4 revArr[i] = arr[arr.length - i -1]; 5 } 6 System.out.println(Arrays.toString(revArr)); 7 8 //[5, 4, 3, 2, 1]
6. 移除数组中的元素
1 // Apache common lang 2 3 int[] arr= { 1, 2, 3, 4, 5 }; 4 int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array 5 System.out.println(Arrays.toString(removed))
标签:
原文地址:http://www.cnblogs.com/fancj/p/5883013.html