英文:
How to convert a ArrayList into 2D array in Java 7
问题
List<String> list = Arrays.asList("1110", "1010", "1011", "1110");
List<Integer> intList = new ArrayList<>();
for (String s : list) {
intList.add(Integer.valueOf(s));
}
int[][] array = new int[intList.size()][];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
array[i][j] = intList.get(j + (list.size() * i));
}
}
我尝试将一个整数列表转换为Java 7中的二维数组。我首先将一个字符串列表转换为整数列表,然后将整数列表转换为二维数组。然后,根据需要执行更多操作。
问题出在这里:
int[][] array = new int[intList.size()][];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
array[i][j] = intList.get(j + (list.size() * i));
}
}
我尝试查看以下链接以解决我的问题:
但是大部分答案都是针对Java 8的,而我不想使用Java 8!我知道这是一个基本的问题,但我被卡住了!有人可以帮我解决这个问题吗?提前感谢!
最终得到的二维数组应该如下所示:
1110
1010
1011
1110
英文:
I am trying to convert a Integer list in a 2D array in java 7. I first converted a String list to Integer and then Integer list to 2D array. Then I will do more operations as required.
What I tired is
List<String> list = Arrays.asList("1110", "1010", "1011", "1110");
List<Integer> intList = new ArrayList<>();
for (String s : list) {
intList.add(Integer.valueOf(s));
}
//the problem is from here
int[][] array = new int[intList.size()][];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
array[i][j] = intList.get(j + (list.size() * i));
}
}
I tried solving my issue looking at this https://stackoverflow.com/questions/2146488/converting-an-arraylist-into-a-2d-array and this https://stackoverflow.com/questions/10043209/convert-arraylist-into-2d-array-containing-varying-lengths-of-arrays but majority of the answers are given in java 8 which I don't want! i know its a basic problem but i am stuck! Can someone help me to fix this? Thanks in advance!
The resulting 2D array should be like
1110
1010
1011
1110
答案1
得分: 2
你可以使用 .charAt()
来获取每个字符串中特定位置的字符。
List<String> list = Arrays.asList("1110", "1010", "1011", "1110");
int[][] array = new int[list.size()][list.get(0).length()];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).length(); j++) {
array[i][j] = list.get(i).charAt(j) - '0';
}
}
英文:
You can use .charAt()
to get the character of the position in every string.
List<String> list = Arrays.asList("1110", "1010", "1011", "1110");
int[][] array = new int[list.size()][list.get(0).length()];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).length(); j++) {
array[i][j] = list.get(i).charAt(j)-'0';
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论