0

I have five arrays.

int Circle_list[] = { Color.BLACK, 20, 20, 50 };
int Rect_list[] = { Color.BLUE, 80, 50, 115, 150 };
int Tri_list[] = { Color.RED, 190, 210, 150, 230, 140, 270 };
int mixColor[];
int mixCoor[];

Now, I want to add the first element(color) from Circle_list[], Rect_list[] and Tri_list[] into mixColor[]. And add all rest numbers into mixCoor[].

How can I do that? Does for loop available for this?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
SPG
  • 6,109
  • 14
  • 48
  • 79
  • The first three arrays are invalid - they contain a mix of `Color` objects and `int` , in Java all the elements in an array must be of the same type (although some polymorphism is allowed, but that's another matter) – Óscar López Dec 06 '11 at 03:18

3 Answers3

4

I do prefer ArrayList, let say in your case it would be like:

ArrayList<Integer> listCircle = ...
ArrayList<Integer> listRect = ...
ArrayList<Integer> listTri = ...
ArrayList<ArrayList<Integer>> storage = new ArrayList<ArrayList<Integer>>();
storage.add(listCircle);
storage.add(listRect);
storage.add(listTri);
Pete Houston
  • 14,931
  • 6
  • 47
  • 60
1
mixColor[] = { Circle_list[0], Rect_list[0], Tri_list[0] };

As for mixCoor (I would also rename your identifier, they're too similar) - does order matter? If not then just loop through the other tables, check if the value of the current index (the counter in the loop) is valid, and if it is, add it to your new table.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Nexion
  • 423
  • 6
  • 18
  • 1
    `System.arrayCopy` tends to be faster for large arrays: http://docs.oracle.com/javase/6/docs/api/java/lang/System.html – jli Dec 06 '11 at 03:05
0

// if you really want to use primitives instead of ArrayLists, this will work:

int mixColor[] = { Circle_list[0], Rect_list[0], Tri_list[0] };
int mixCoor[] = new int[Circle_list.length + Rect_list.length + Tri_list.length - 3];

int i, j=0;

for(i=1; i<Circle_list.length; ++i, j++) {
    mixCoor[j] = Circle_list[i];
}
for(i=1; i<Rect_list.length; ++i, j++) {
    mixCoor[j] = Rect_list[i];
}
for(i=1; i<Tri_list.length; ++i, j++) {
    mixCoor[j] = Tri_list[i];
}

// OR more general solution:

j = 0;
int[][] shapes = {Circle_list, Rect_list, Tri_list};
for (int[] shape : shapes) {
    for(i=1; i<shape.length; ++i, j++) {
        mixCoor[j] = shape[i];
    }
}

// If you want to use ArrayLists instead, see also: How to convert List<Integer> to int[] in Java?

Community
  • 1
  • 1