- 声明数组
String[] aArray = new String[5];
// arrays[0] = "1";//向数组中添加元素
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};
- 打印数组
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d
System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
- 数组转List
String[] arrays = {"1","2","3"};
List<String> list = Arrays.asList(arrays);//Arrays->List
- List 转数组
ArrayList<String> arrayList = new ArrayList<>();
String[] arrays = new String[arrayList.size()];
arrayList.toArray(arrays);
- 合并数组
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// org.apache.commons.lang3.ArrayUtils;
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
- 移除数组中的元素
int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
6.复制数组
int[] arr1 = {1,2,3};
int[] arr2 = {1,2,3,4,5,0};
//复制数组,原数组不变
int[] newarr1 = Arrays.copyOf(arr1,5); //copyOf()方法
int[] newarr2 = Arrays.copyOfRange(arr2,1,4); //copyOfRange()方法
String s1 = Arrays.toString(newarr1);//输出1,2,3,0,0或者1,2()
String s2 = Arrays.toString(newarr2);//2,3,4
7.数组查询(二分法)
String[] str = new String[]{"ab","cd","Ab","gh"};//String[] 排序相比较首字母,以此类推
Arrays.sort(str);
int index1 = Arrays.binarySearch(str,"cd"); //为1
int index2 = Arrays.binarySearch(str,"de");
int index3 = Arrays.binarySearch(str,0,2,"cd"); //为1
System.out.println("index1:"+index1+";index2:"+index2+";index3:"+index3);//1,-4,1
- 把数组中的元素用指定的分隔符连接起来
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c
- 反转数组
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]