Take the 2-minute tour ×

I have a 2D game that uses two integer arrays to track x and y coordinates as shown below:

private int gridX[] = { 0,0,0,0,0 }
private int gridY[] = { 0,0,0,0,0 }

The problem is I can have a LOT of objects on the screen that needs to be tracked. Is there a way to add integers / create new blocks as needed? IE in a loop, do something like gridX[].add(); or something like that. I'm relatively new to java and droid development and I'm having trouble finding a good tutorial or example that shows how to do this without having to initialize the gridX and gridY to sizes of 100 or so.

This is important, as I am about 90% sure that all those unused 0's are causing androids garbage cleanup to lag my application.

share|improve this question
In Java a plain array cannot change its size once its been created. ArrayList is probably what your looking for as @MBU said. –  FoamyGuy Apr 7 '11 at 19:42
It would be wise to store corresponding x and y coordinates in the same object so that they are linked together and harder to confuse. –  Matthew Willis Apr 7 '11 at 19:44
add comment

2 Answers

up vote 3 down vote accepted

Why not also use the Point class?

List<Point> points = new ArrayList<Point>();

points.add(new Point(0, 0));
points.add(new Point(50, 70));

Point point = points.get(1);
Log.d("MyApp", String.format("The point is: (%d, %d)", point.x, point.y);

This way you are keeping track of your x and y coordinates together and there is less opportunity for error.

share|improve this answer
Very good idea! =) –  MBU Apr 7 '11 at 19:57
Thanks, this sounds like the best solution. Do you know if using this method if I can specify the index? Like points.add(INDEX, values); ? –  Tom Apr 7 '11 at 19:58
Yes, you can do that. However, keep in mind that inserting doesn't perform very well (in general, the later elements have to be "moved over" to make room) –  Matthew Willis Apr 7 '11 at 20:01
Awesome, was looking at keeping a specific object the number 0 object no matter what, but the obvious simple solution there is to just create it first. Thanks a lot for your help, I'm pretty sure this will drastically increase performance. –  Tom Apr 7 '11 at 20:06
Actually int[] will always have better performance than ArrayList<Integer> or ArrayList<Point> unless you are copying and moving around sections of your array. The bonus of the methods in the answers here is that they make your life easier as a programmer, and the performance difference is not big enough to justify the headache of using int[]. –  Matthew Willis Apr 7 '11 at 20:13
show 10 more comments

Why dont you use an array list instead of an Integer array? that way you can dynamically add items to the list

ArrayList<Integer> myList  = new ArrayList<Integer>();

share|improve this answer
Agreed. It can be very annoying to change the size of an array dynamically. It can be done, but it usually isn't pretty. –  Alexander Miles Apr 7 '11 at 19:42
add comment

Your Answer


