[Solved] How do i convert a Set into 2D array in java? [closed]


Let be a:

public class MyClassWhithFourFields {
 String field1;
 int field2;
 Object field3;
 double field4;
}

Now you can declare a set with this template:

Set<MyClassWhithFourFields> mySet = new HashSet<MyClassWhithFourFields>();

In your Set are your objects, which has 4 fields.

If you want to declare a 2 dimension array, than what type should be?
– the most common parent can be, and in this case it is the Object.

So declare a function an implement it:

Object[][] transformSetTo2dArray(Set < MyClassWhithFourFields > mySet) {
 if (mySet == null) {
  return null;
 }
 Object[][] result = new Object[4][mySet.size()];
 int j = 0;
 // iterate the set:
 for (MyClassWhithFourFields myObject: mySet) {
  myObject[0][j] = myObject.field1;
  myObject[1][j] = myObject.field2;
  myObject[2][j] = myObject.field3;
  myObject[3][j] = myObject.field4;
  j++;
 }
 return result;
}

solved How do i convert a Set into 2D array in java? [closed]