I often find myself using arrays in a class and needing to keep track of which value in the array is currently in use. For example, imagine a camera system that has an array of cameras, and I need to keep track of which one is currently active. The way I've always done this is by creating the array and an int variable called cameraIndex or something like that. Then when I switch array values, I change the value of cameraIndex. This does work, but I've always felt there's probably a better way to do this. It seems unnecessary to create an extra variable to keep track.
Here is a quick example:
class Camera{
// Pretend there's camera logic in here.
}
class User{
public setCamera(Camera newCamera){
// Logic for having the user look through a new camera.
}
}
class CameraSystem{
private User user;
private Camera[] cameraList;
private int cameraIndex = 0;
public void goToNextCamera(){
cameraIndex++;
user.setCamera(cameraList[cameraIndex]);
}
}
You're correct in your approach that there is a way to manage the current active camera without explicitly keeping track of its index using an additional variable such as i
. One approach is to directly store the reference to the current active camera within the CameraSystem
class.
class CameraSystem {
private User user;
private Camera[] cameraList;
private Camera activeCamera; // Store the reference (not index) of the camera
public CameraSystem(User user, Camera[] cameraList) {
this.user = user;
this.cameraList = cameraList;
this.activeCamera = cameraList[0];
// basic setup
}
public void goToNextCamera() {
int nextIndex = (getIndex(activeCamera) + 1) % cameraList.length; // This is where you can store the next camera in its new index.
activeCamera = cameraList[nextIndex];
user.setCamera(activeCamera);
}
private int getIndex(Camera camera) {
for (int i = 0; i < cameraList.length; i++) {
if (cameraList[i] == camera) {
return i;
}
}
return -1; // If camera isn't there
}
}
Here, in the CameraSystem
class, it directly stores the reference to the active camera (activeCamera
). When you want to switch to the next camera, you iterate through the cameraList
array to find the index of the current active camera, then move to the next index (with circular iteration to wrap around when reaching the end of the array). Finally, you update the activeCamera
reference and set it for the user. This approach avoids the need for an additional variable like cameraIndex
.