This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes better way? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "better way?" Watch "better way?" New topic
Author

better way?

david lightman
Ranch Hand

Joined: Nov 03, 2004
Posts: 82
I basically want to check a key in a hashtable (dog) and if there is a key named dog pull the value which is his name.

but it seems like alot of moving around, is there a better way to do this?

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

You can factor out the variable "dog", and you don't need to construct a new Hashtable (very inefficient, and totally unnecessary!)




You could remove the check for null if you assured that getHashTableData() never returned null -- generally a smarter, cleaner way to program. Then you could write it in one line:

String dogName = (String) myClass.getHashTableData().get("DOG");


[Jess in Action][AskingGoodQuestions]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Avoid ever having a null collection. It's much better to assume you have a valid collection and check the size for something greater than zero. Also, unless you have an old version of Java you should specifiy what is in your collection. Never use Hashtable: use HashMap. You can synchronize access to your HashMap, if needed, and use it consitently everywhere. Finally, always declare the collection interface not the concrete type.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: better way?