Java数组与list相互转换的一些坑


Java数组与list相互转换的一些坑

数组转list

  使用Arrays.asList()方法,将返回值转换成java.util.ArrayList后可实现ArrayList的全部功能。

String[] testArr = new String[]{"aa","bb","cc"};
List<String> testList = new ArrayList<>(Arrays.asList(testArr));
  值得一提的是,如果按照以下方式进行转换,得到的list并不能进行增删,原因在于返回值并不是java.util.ArrayList,而是java.util.Arrays.ArrayList,并不是同一个类。
String[] testArr = new String[]{"aa","bb","cc"};
List<String> testList = Arrays.asList(testArr);
testList.add("dd");
System.out.println(testList);
| 运行时报错 | | ------------------------------------------------------------ | | Exception in thread "main" java.lang.UnsupportedOperationException | | at java.base/java.util.AbstractList.add(AbstractList.java:153) | | at java.base/java.util.AbstractList.add(AbstractList.java:111) | | at Main.main(Main.java:59) |

  在做题过程中遇到了一个坑,在二维列表的处理上出现了一些问题。不能按照如下方式进行add操作。

PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> {
	if (a[0] != b[0])
		return a[0] - b[0];
	else if (a[1] != b[1])
		return a[1] - b[1];
	else if (a[2] != b[2])
		return a[2] - b[2];
	else
		return a[3] - b[3];
});
......
List<List<Integer>> ans = new ArrayList<>();
while (!pq.isEmpty() && ans.size() < k) {
    int[] cur = pq.poll();
    ans.add(Arrays.asList(new int[]{cur[2], cur[3]}));
}

//不兼容的类型。实际为 java.util.List<int[]>',需要'java.util.List<java.lang.Integer>'
改成如下形式依然报错
while (!pq.isEmpty() && ans.size() < k) {
    int[] cur = pq.poll();
    ans.add(new ArrayList<>(Arrays.asList(new int[]{cur[2], cur[3]})));
}

//无法推断参数
  查阅资料后得知,int数组到List需要分为两步操作,即先转换成Integer数组,再转换成List,这里给出一种java8的stream流方法进行一步转换,给出正确的过程如下:
while (!pq.isEmpty() && ans.size() < k) {
    int[] cur = pq.poll();
    ans.add(Arrays.stream(new int[]{cur[2], cur[3]}).boxed().collect(Collectors.toList()));
}
  不失一般性地给出int[]到List的标准转换:
List<Integer> list = Arrays.stream(数组名).boxed().collect(Collectors.toList());

list转数组

  目前的方法还是使用toArray()方法,在toArray()中构造新数组,如下。

List<String> testList = new ArrayList<>() {{
	add("aa");
	add("bb");
	add("cc");
}};
String[] testArr = testList.toArray(new String[0]);
| 打印结果 | | ---------------------------- | | aa | | bb | | cc | | [Ljava.lang.String;@776ec8df |

  同样的,如果需要将List转换为int[]数组同样需要两步操作。我们这里仅给出java8的流方法。

List<Integer> testList = new ArrayList<>(){{
	add(10);
	add(20);
	add(30);
}};
int[] testArr = testList.toArray(new int[0]);
//无法解析方法 'toArray(int[])'
int[] testArr = testList.toArray(new Integer[0]);
//不兼容的类型。实际为 java.lang.Integer[]',需要 'int[]'
......

List<Integer> testList = new ArrayList<>(){{
	add(10);
	add(20);
	add(30);
}};
int[] testArr = testList.stream().mapToInt(Integer::valueOf).toArray();
//能够正确转换
  不失一般性的有:
int[] 数组名 = 列表名.stream().mapToInt(Integer::valueOf).toArray();
[toc]


文章作者: Commander
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Commander !
  目录