ssb
ssb

Reputation: 209

Pointer in Java

I have a 450*300 image. Buttons are distributed on that image based on some rules. Each button suppose to cost only one pixel, (271,28) and (272,28) represent two different buttons. I wanna track existing button with its x,y location. Intuitively, I thought it's convenient and O(1) complexity to access the Button on image by subscript, so I try to use a 2-dimensional array.

JButton[][] btnArray= new JButton[450][300];

As button numbers are limited within 100, so that's not what I want to do which allocate unnecessary redundant space. I just need 450*300 pointers, pointing to some specific JButton instance or being null. Can I implement such mechanism in Java?

Thanks, enjoy fool's day tomorrow.

Upvotes: 1

Views: 245

Answers (5)

Paul Ruane
Paul Ruane

Reputation: 38580

I think, to avoid cresting a large array of null references, I would be tempted to, instead, initiliase a Map of buttons keyed on location, e.g. using Point as the key.

Map<Point, JButton> buttons = new HashMap<Point, JButton>();

Finding out whether a button exists at a given location is now a simlle map operation

buttons.Contains(new Point(123, 456));

And the map key set gives you the list of locations.

Upvotes: 1

cgull
cgull

Reputation: 1417

If you're limited to 100 buttons, instead of creating an array of length 450*300 = 135000, why not create an array of length 100 (or even an ArrayList so it only uses as much memory as you have allocated buttons) that stores an object containing the JButton and its x and y coordinates in the image. It all depends on whether memory usage or speed is more important for your application.

Upvotes: 0

RollingBoy
RollingBoy

Reputation: 2817

JButton[][] btnArray= new JButton[450][300];

In fact, this statement allocated 2-d array for JButton references instead of JButton objects. It has been done indeed.

Upvotes: 0

asdfjklqwer
asdfjklqwer

Reputation: 3594

What you've done there is allocating space for 450x300 pointers since reference variables in Java are effectively pointers. You now just need to go through and initialise them with object references or null.

Upvotes: 0

Bala R
Bala R

Reputation: 108937

Actually JButton[][] btnArray= new JButton[450][300]; does not create/allocate memory for 450*300 buttons. you are just creating 450*300 reference variables.

you can create button instances as needed

btnArray[5][5] = new JButton("5, 5");

and everything else that's not initialized like this would be null.

Upvotes: 2

Related Questions