-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

8
  • 1
    What is the condition behind 1D to 2D ? Give an example in you post
    – Eklavya
    Jul 25, 2020 at 15:57
  • 1
    edit your question and post the resulting 2D array that you want to get from the example list in your question.
    – Abra
    Jul 25, 2020 at 15:58
  • Ok I edited it! Please have a look Jul 25, 2020 at 16:01
  • 3
    The example you give at the end doesn't look like a 2D array. Jul 25, 2020 at 16:07
  • 1
    Every string represent 1D array ? means {1,1,1,0}{1,0,1,0} ...?
    – Eklavya
    Jul 25, 2020 at 16:11

1 Answer 1

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';
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.