和数组有关的一些函数

1. 字符数组与字符串转换

char[] str = s.toCharArray();

String s = String.valueOf(str);
String s = new String(str);

2. 将List转换为数组

List<String> list = new ArrayList<>();
String[] strs = list.toArray(new String[list.size()]);

注意1:不能转成int[],只能是Integer[]
原因是toArray得到的是Integer[],且Interger[]不能转换为int[]

List<Integer> list = new ArrayList<>();
int[] nums = list.toArray(new int[list.size()]);//error
int[] nums = (int[])list.toArray(new int[list.size()]);//error
//正确的
Integer[] result = list.toArray(new Integer[list.size()]);

注意2:List中可以放数组,且可转换为二维数组

List<int[]> temp = new ArrayList<>();
int result[][] = temp.toArray(new int[temp.size()][]);

3. 通过数组创建List / 从可变长参数表中创建List

List list1 = Arrays.asList(10,20,30,40);
注意:比正常创建,并add慢

String[] strs = {“red”, “green”, “yellow”};
List list2 = Arrays.asList(strs);
注意:List list3 = Arrays.asList(nums);
nums不能是int[] 类型

4. 创建二维数组,其中的每个数组不是等长度

  • 方法一
int[][] nums = new int[3][];
int[] num1 = {1,2,3};
int[] num2 = {4,5,6,7,8,9};
int[] num3 = {10,11,12,13,14,15,16,17};
nums[0] = num1;
nums[1] = num2;
nums[2] = num3;
  • 方法二
int[][] a = new int[][]{{1,2,3},{2,3}};
//可拆开写
int[][] a;
a = new int[][]{{1,2,3},{2,3}};
  • 方法三【注意:数组常量只能在初始化器中使用】
int[][] a = {{1,2,3},{2,3}};
不能写为
int[][] a;
a = {{1,2,3},{2,3}};

5. 数组排序、List排序

  • int[] num
    List list
    Arrays.sort(num);

    • 利用拉姆达表达式构造Comparator对象
      intervals是一个二维数组int[][]
      Arrays.sort(intervals, (a,b) -> a[0]-b[0]);
  • Collections.sort(list);

6. 数组复制
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
src:源数组;
srcPos:源数组要复制的起始位置;
dest:目的数组;
destPos:目的数组放置的起始位置;
length:复制的长度。
注意:src and dest都必须是同类型或者可以进行转换类型的数组

System.arraycopy(nums2, 0, nums1, 0, i2+1);

7. Arrays.fill(a1, value)【a1引用的只能是一个一维数组】
a1为数组变量,用value填充a1中的每个元素
参考

8. 创建匿名数组
res.add(new int[]{0,1,2});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值