7 数组

数组

数组概念

数组就是存储数据长度固定的容器,保证多个数据的数据类型要一致。

什么是数组?
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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值