0

I have a list of objects and I'll need to access a specific one based off of random user input corresponding to an id. My limited knowledge at this point led me to something like:

String id; 
if(id.equals("apple")){ //fixed silly error, thanks
    return objectList.id.memberName; 
} //etc...

Is this possible, or is there a better approach?

  • A word to the wise on comparing strings in Java: you should use `equals` to compare strings, not `==` (the code you posted with only `=` won't even compile because it's assigning to `id` in the if condition, not comparing). In other words, the second line of your code should be `if (id.equals("apple")) {`. – Adam Mihalcin Mar 28 '13 at 23:34

4 Answers4

2

Sounds like you want a HashMap.

It works like a telephone directory - you put in keys and values, and use the key to look up a value (much like you'd use someone's name to look up their number in a telephone directory.)

Your example also wouldn't work at all, because you're using = in the if statement, which is an assignment statement rather than an equality check. == is what you were probably trying to get, but in this case you shouldn't use that either - instead use .equals() which you should always use when strings are concerned.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
1
HashMap<String, SomeValueObject> myMap = new HashMap<String, SomeValueObject>();
myMap.put("apple", value);
String id;
if (id.equals("apple")) {
    return myMap.get("apple");
}

Essentially you instantiate a HashMap that has two parts to it; a Key and a Value (respectively. When I do myMap.get("apple"), it searches for the KEY "apple". I did myMap.put("apple", value) which makes the Key "apple" be mapped to a certain value that you want.

Also you need to use id.equals("apple") because a String is an object, and if you tried id == "apple" (which I think you meant), it will not work because it will not compare the value of the String but rather the address of it.

kikiotsuka
  • 79
  • 8
0

@berry120 has provided a practical answer. In general, it sounds like you want to lookup values based on some key. Look at the Map interface and what the JDK offers for concrete implementations.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
0

The value of a variable is only available at run time. On the other hand, a variable name must be known at compile time. So no, you cannot do this exactly the way you are asking. Using a Map will probably be the best solution to your problem.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268