数组
数组概念
数组就是存储数据长度固定的容器,保证多个数据的数据类型要一致。
什么是数组?
int[] nums;//声明一个数组
nums = new int[10];//给数组开辟内存空间
int[] num2=new int[]{1,34,4,5,67}
数组存储的数据类型[ ] 数组名字 = new 数组存储的数据类型[数组长度];
~~ 数组存储的数据类型 数组名字[ ] = new 数组存储的数据类型[数组长度]; ~~
数组有定长特性,长度一旦指定,不可更改
数组的长度属性: 每个数组都具有长度,而且是固定的,Java中赋予了数组的一个属性,可以获取到数组的长度,语句为:数组名.length ,属性length的执行结果是数组的长度,int类型结果。由次可以推断出,数组的最大索引值为数组名.length-1。
数组的遍历
for循环
int []demo2 =new int []{1,2,3};
for (int i = 0; i < demo2.length ; i++) {
System.out.println(demo2[i]);
}
foreach循环
for (int demo1:demo2) {
System.out.println(demo1);
}
数组常用API
输出数组 Arrays.toString()
int[] array = { 1, 2, 3 };
System.out.println(Arrays.toString(array));
数组转List Arrays.asList()
String[] array2 = {"a", "b", "c", "d"};
System.out.println(array2); // [Ljava.lang.String;@13b6d03
List list = new ArrayList(Arrays.asList(array2));
System.out.println(list); // [a, b, c, d]
list.add("GG");
System.out.println(list); // [a, b, c, d, GG]
数组转Set Arrays.asList()
String[] array = { "a", "b", "c", "d", "e" };
Set set = new HashSet(Arrays.asList(array));
System.out.println(set);
List转数组 toArray()
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
String[] array = new String[list.size()];
list.toArray(array);
for (String s : array)
System.out.println(s);
数组中是否包含某个值
String[] array = { "a", "b", "c", "d", "e" };
boolean isEle = Arrays.asList(array).contains("a");
System.out.println(isEle);
数组复制
int array[] = new int[] { 1, 2, 3, 4 };
int array1[] = new int[array.length];
System.arraycopy(array, 0, array1, 0, array.length);
数组合并
int[] array1 = { 1, 2, 3, 4, 5 };
int[] array2 = { 6, 7, 8, 9, 10 };
int[] array = org.apache.commons.lang.ArrayUtils.addAll(array1, array2);
System.out.println(Arrays.toString(array));
String数组转字符串(使用指定字符拼接)
String[] array = { "a", "b", "c" };
String str = org.apache.commons.lang.StringUtils.join(array, ", ");
System.out.println(str);