I am creating an object in Java. One of its attributes is a grid reference - ints x, y & z.
Rather than creating a variable for each, is there a better way to store these?
I am creating an object in Java. One of its attributes is a grid reference - ints x, y & z.
Rather than creating a variable for each, is there a better way to store these?
Create a record-like class, GridReference:
public class GridReference {
public int x;
public int y;
public int z;
}
You could instantiate it as:
GridReference gridReference = GridReference();
And assign the individual values via:
gridReference.x = 1;
gridReference.y = 0;
gridReference.z = 0;
Accessible via:
gridReference.x;
gridReference.y;
gridReference.z;
You could flesh the class-out to a more secure object as:
public class GridReference {
private final int _x;
private final int _y;
private final int _z;
public GridReference(int x, int y, int z) {
_x = x;
_y = y;
_z = z;
}
public getX() {
return _x;
}
public getY() {
return _y;
}
public getZ() {
return _z;
}
}
And instantiate it as:
GridReference gridReference = new GridReference(1, 0, 0);
Assigning the values at the same time. These would be accessed via:
gridReference.getX();
gridReference.getY();
gridReference.getZ();
(To change the values, you'd need to reassign the reference to a new GridReference though.)
You can use an array for them
class MyClass {
private final int [] gridRef = new int[3];
public MyClass( int x, int y, int z ) {
gridRef[0] = x;
gridRef[1] = y;
gridRef[2] = z;
}
public int getX() {
return gridRef[0];
}
public int getY() {
return gridRef[1];
}
public int getZ() {
return gridRef[2];
}
}
That would be a read only access to the grid reference.
I'm not sure if that is "better" though. What do you want to achieve?