What's an efficient way to test if a player has clicked on one of many objects in a Java game?
<p>This is a basic question, but since I haven't been coding Java for long I'd like to get an opinion from someone with more experience. Let's say I have a game in Java in which there are many objects (on the order of 30) on the screen. The player can click on an object and each object handles a mouse click differently.</p>

<p>My question is: if the player clicks on the game window, what's a good way to test if he clicked one of the objects, and if so, trigger that object's mouse click event handler?</p>

<p>Here's what I've come up with so far: my applet has a mouse listener and it could also have a list of all game objects currently in existence. The applet's event handler could traverse the list of objects and see if the coordinates of the click are inside that object's bounding box through something like <code>gameObject.isInsideBBox(int mouseX, int mouseY)</code>.</p>

<p>This would be simple to set up, but I feel like it would be inefficient. If the number of objects is large then the program would have to traverse the list every time a user clicks. Couldn't this become a performance issue?</p>

<p>One alternative would be to have each object have its own MouseListener and add all the objects to some sort of global container. Would this method be more efficient in terms of performance than the above? One other concern is that these Component and Container objects seem to be defined in Java's Swing library, but I'm not using Swing for any other purposes. I have the feeling that would be a misuse of the library.</p>

<p>Any feedback/comments?</p>

<p>(I'd be interested to know if these methods would port over to Android. I realize that's a different topic, but if you have any insight on that, I'd appreciate if you could let me know.)</p>
