Admiral Trigger Happy Admiral Trigger Happy - 2 months ago 10
Java Question

Java select object instance based on variable

I have a really annoying assignment which requires me to create 3 instances of a object and I need to create methods to modify and access them for use in another class.
I know the simplest and best way to do this would be to use an array, but I'm not supposed to know about those yet and the assignment requires I NOT use them.

So basically I'm looking for a way to interact with each of the objects based on another variable.

For example I have the following instances of my object:

object1
object2
object3

What I want to be able to do is create a variable objectNo, and use the number of that variable to select object 1, 2 or 3

Instead of having a bunch of if statements and writing the same code 3 times where the only difference is the object name as I have it currently below:

public void updateObject (int argNo, String argName)
{
private int objectNo = argNo;
private String productName = argName;
if (objectNo == 1)
{
object1.name = productName

}

else if (objectNo == 2)
{
object2.name = productName
...
}


Any suggestions, I'm new to Java and this is doing my head in.

Answer

Instead of having a bunch of if statements and writing the same code 3 times where the only difference is the object name as I have it currently below:

If you want to save yourself from copy & pasting code you can use a variable in this case, for example:

MyObject objectToChange;

if (objectNo == 1) {
    objectToChange = object1;
} else if (objectNo == 2) {
    objectToChange = object2;
} else if (objectNo == 3) {
    objectToChange = object3;
} else {
    throw new IllegalArgumentException(Integer.toString(objectNo));
}

objectToChange.name = productName;

Whether this actually helps you out depends on how much stuff you're doing with objectToChange.

You also could use a switch instead of if...else but it doesn't really save you anything except making the code line up neatly.

Of course an array or Map is the correct way to do something like this in the real world.

Comments