[英]2D ArrayList to a normal array java
Basically, I am creating a dynamic 2d ArrayList. 基本上,我正在创建一个动态2D ArrayList。
private ArrayList<char[]> myArray;
This code below is done in loop. 下面的代码是循环完成的。 A few random strings of the "same length" is given to store the all the characters in array.
给出了一些“相同长度”的随机字符串,以将所有字符存储在数组中。
while (body) 而(身体)
char[] temp = myString.toCharArray();
myArray.add(temp);
So after all the characters are inserted into the ArrayList, I want to convert myArray into a normal array. 因此,在将所有字符插入ArrayList之后,我想将myArray转换为普通数组。 (why? because it is going to be useful in future) And I think I am doing it wrong here:
(为什么?因为将来会有用),我认为我在这里做错了:
charArray = (char[][]) myArray.toArray();
//declaration of 'charArray' is already done at the start of the class.
So the problem is when I try to print the whole 'charArray' just to check, or any elements, I get an "java.lang.NullPointerException" error. 所以问题是当我尝试打印整个'charArray'只是为了检查或任何元素时,出现“ java.lang.NullPointerException”错误。
So how do I covert the 2d ArrayList into a normal array ? 那么如何将2d ArrayList转换为普通数组呢? I tried many different sources but didn't help.
我尝试了许多不同的资源,但没有帮助。
Thank you. 谢谢。
Not sure if you want a char[]
or a char[][]
in the end. 不确定到底要使用
char[]
还是char[][]
。 See below both options: 参见以下两个选项:
public static void main(String... args) throws Exception {
List<char[]> myArray = new ArrayList<char[]>();
myArray.add("string1".toCharArray());
myArray.add("string2".toCharArray());
myArray.add("string3".toCharArray());
char[][] charArray2D = myArray.toArray(new char[0][0]);
System.out.println(charArray2D.length); //prints 3
StringBuilder s = new StringBuilder();
for (char[] c : myArray) {
s.append(String.copyValueOf(c));
}
char[] charArray1D = s.toString().toCharArray();
System.out.println(charArray1D.length); //prints 21
}
Something like this: 像这样:
public static void main(String[] args) {
List<char []> list = new ArrayList<char []>();
list.add("hello".toCharArray());
list.add("world !".toCharArray());
char[][] xss = list.toArray(new char[0][0]);
for (char[] xs : xss) {
System.out.println(Arrays.toString(xs));
}
}
Output: 输出:
[h, e, l, l, o]
[w, o, r, l, d, , !]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.