0

I try to set data from list to two multidimensional array. Normally I can set data to two multidimensional array like this:

Object[][] newData = {
        { "test", "test2", 15.98, 0.14, "+0.88%",
                32157250 },
        { "AAPL", "Apple Inc.", 126.57, -1.97, "-1.54%", 31367143 }"

However I want to set data dynamically from list . I have a method which returns a list:

List<User> user = listUser(id);
static User { 
     private int id;
     private String name;
     and getter(...),setter(..).

I need to set user from listUser(id) method to Object[][] array.

I try to do it but I couldn't get succesful result:

for (int i=0;i<user.size();i++){
            for(int j=0;j<user.size();j++){
                newData[i][j]=user.get(i).getName();
            }
        }

Could you help me?

3
  • This is a suggestion on your case: How about using List<List<User>> instead of Object[][]? Commented Apr 16, 2017 at 20:30
  • Is your user is holding only two fields such as id & name? Commented Apr 16, 2017 at 20:32
  • actually, I will popluate My list result to JTable in java swing. And i see generally that they put object to JTable. Thats why i decide to set it to Object[][] Commented Apr 16, 2017 at 20:38

2 Answers 2

1

The columns are fixed, i.e., 0,1,2,etc.. and you need to iterate and set the data for each row as shown below:

for (int i=0;i<user.size();i++){
  for(int j=0;j<user.size();j++){
   newData[i][j]=user.get(i).getId();//get id for each rowand set to 0th column
   newData[i][j]=user.get(i).getName();
   newData[i][j]=user.get(i).getX();//other fields
   newData[i][j]=user.get(i).getY();//other fields
  }
}

Also, it is not a good idea to use Object[][] (not sure for what reason you are using this) as it requires explicit casting while retrieving/using the fields.

Sign up to request clarification or add additional context in comments.

1 Comment

newData is String[][] array. You might want to convert the member variables to String before assigning.
0

It looks like the data is well structured. I would create a class and keep a single-dimension array of your private "CompanyStock" class instead of using a dangerous 2d Object[][] array.

Comments

Your Answer

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