Hey folks.

I'm trying to make a new Fruit object each time aMethod is called.
The new Fruit object's name must be unique.

The problem is that the name of this Fruit object is the same name as one of the parameters of aMethod - this name is unfortunately the best name for the new object I think.

What can I do make it work?
Whatever the new Fruit object is called, the name must contain whatever is passed to aMethod.

Please help!

public void aMethod (String someFruit){
    Fruit someFruit = new Fruit(someFruit);    

//The Fruit object's name is the same name as the parameter. 
//The parameter passed to Fruit is the String that's provided to this method (aMethod). 
5 Years
Discussion Span
Last Post by JamesCherrill

What exactly do you mean by the object's name? Objects in Java do nor have names. You can have an instance variable String name; in the Fruit class and set that.


... part 2
if you want to create a reference variable with that name then the answer is "you can't". Even if there were a way to do that, there's no way to use a variable whose name isn't known at compile time (ignoring advanced Reflection techniques).

If you want to be able to refer to your Fruit objects based on their name, then you can use a Map, eg

HashMap<String, Fruit> namedFruit = new HashMap<String, Fruit>();
namedFruit.add("Apple",  new Fruit("Apple"));
Fruit f = namedFruit.get("Apple");

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.