Convert Arraylist to Object[][]

Asked

Viewed 90 times

2

How to convert an Arraylist to a 2D Object.

My Current Code:

ArrayList<String> a = null;
    a = new ArrayList<String>();                    
            a.add("ABC");
            a.add("DEF");
            a.add("1");
            a.add("1");

//Converter para Object 2D
int n = a.size();
System.out.println("Tamanho do Array: "+n);
Object[][] data = new Object[n][];
for (int i = 0; i < n; i++) 
    data[i] =    a.toArray();

This way I can get the first value of Arraylist, but it repeats in all positions, I believe the reason is because I am not asking for other positions of the arraylist in the line data[i] = a.toArray();, I tried to change that line to data[i] = a.get(i); more then I get the error "Type Mismatch: cannot Convert from String to Object[]"

  • What you should have in the second dimension?

  • @Maniero, in my arraylist I obtain data from a database table with the following structure (Metal Unit, Steel, Furnace Time, Uniformity). I need each line received to be stored in a 2D Object, but I’m with no idea how to do this.

  • 1

    So there is a lot of information missing there, without understanding the problem completely has no way to answer this.

  • Okay, I’ll update the question.

  • This question smells like this: https://pt.meta.stackoverflow.com/q/499/132

  • @Victorstafusa, you’re right, I’m thinking of a way to better present my problem.

Show 1 more comment

1 answer

0

ArrayList<String> a = null;
a = new ArrayList<String>();
a.add("ABC");
a.add("DEF");
a.add("1");
a.add("1");        

//Converter para Object 2D
int n = (a.size() + 1) / 2;
System.out.println("Tamanho do Array: " + n);
Object[][] data = new Object[n][n];
int temp = 0;
for (int i = 0; i < data.length; i++) {
    for (int j = 0; j < data.length; j++) {
        data[i][j] = a.get(temp);
        temp++;
    }
}

for (int i = 0; i < data.length; i++) {
    System.out.print("[");
    for (int j = 0; j < data.length; j++) {
        System.out.print(" " + data[i][j] + "");
    }
    System.out.println("]");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.