1

My question is similar to:

Creating a variable name using a String value.

But I was hoping to take a different angle on it.

The reason for wanting to name each object is so I can call on the specifically later, and create multiple objects using the same statement. Ideally, this is what I want to work.

String dogName = reader.nextLine();

int legs  = reader.nextInt();

char beenFed = reader.nextChar();

new dogName = dog(dogName, legs, fed) `

I know java can't accept the variable as the object name. But suppose I want to create three dogs, "Red", "Blue" and "Jeff", how could I configure it, so that later the user can enter

Red.getLegCount();

Blue.hasBeenFed();

etc.

How else can I create this scenario? If I'm wanting to make many differently named Dog objects, how do I do it? And if it isn't a good idea, what could I do instead?

PS - First post on Stack Overflow. Please guide with etiquette/formatting.

Community
  • 1
  • 1
xkem
  • 31
  • 4

1 Answers1

4

Why don't you use a HashMap? What you basically need is a set of key-value pairs. This is exactly what HashMap does. A good link to start off: http://tutorialswithexamples.com/java-map-and-hashmap-tutorial-with-examples/

Make your Dog class with dogName, legs, beenFed, other attributes.. Next, define a HashMap<String,Dog> with key being as dogName and Dog being the entire Dog object with all attributes. e.g

Dog red = new Dog("red",5,true);
hashmap.put(red.dogName, red);

Later if you want to access the Dog object, do olddog = hashmap.get("red"). Now, you can do anything - olddog.getLegs() ...

shiladitya
  • 2,290
  • 1
  • 23
  • 36
  • 1
    +1. A Hashmap or simply a collection of dog objects would suffice. If you have some natural key for your object (like dog name, or combination of properties of a dog), then you can simply grab it from the collection. – Mr Moose Apr 21 '13 at 05:10
  • IT doesn't seem like objects are being created using HashMap - although maybe I am wrong. – xkem Apr 21 '13 at 05:11
  • I still need to be able to query a dog object using getLegCount() from the dog class. – xkem Apr 21 '13 at 05:13
  • I've had a look at HashMap, and that's a good solution, however using a key works too, then using a getKey() function in conjunction with a compare to bring up a specific object. Thanks for your help! – xkem Apr 22 '13 at 10:50