-2

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 Converting an ArrayList into a 2D Array and this 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

Rajnish Sharma
  • 390
  • 2
  • 14

1 Answers1

2

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';
    }
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57