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?

1
  • 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) Commented Dec 6, 2011 at 3:18

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

System.arrayCopy tends to be faster for large arrays: docs.oracle.com/javase/6/docs/api/java/lang/System.html
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?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.