Results 1 to 6 of 6
- 08-28-2010, 01:57 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 6
- Rep Power
- 0
What to modiy to get the output as HelloWorld
Why is the ouput not coming as Hello World?
What is to be modified?
import java.util.*;
class Key {
int m_keyVal;
Key( int val) {
m_keyVal = val;
}
}
public class TestKey {
static HashMap<Key,String> table = new HashMap<Key,String>();
static public void addToMap( int val, String str) {
Key key = new Key( val);
table.put( key, str);
System.out.println(key);
System.out.println(str);
}
static public String getString( int val) {
Key key = new Key( val);
System.out.println(table.get(key));
return table.get( key);
}
public static void main(String[] args) {
addToMap( 1, "hello");
addToMap( 2, "world");
System.out.println( getString( 1) + ", " + getString( 2) );
}
}
- 08-28-2010, 02:01 AM #2
What do you get as output with the program you posted?
- 08-28-2010, 02:13 AM #3
Member
- Join Date
- Aug 2010
- Posts
- 6
- Rep Power
- 0
its all null
- 08-28-2010, 02:36 AM #4
You need to provide an equals and hashcode method to the Key class.
Read the API doc for the get method. And Object class's equals method.
- 08-28-2010, 02:44 AM #5
Member
- Join Date
- Aug 2010
- Posts
- 6
- Rep Power
- 0
Can u tell me how to do that?I am not able to get u.
- 08-28-2010, 02:50 AM #6
Do you know how to add methods to classes?
If not, back to the books.
Read the API doc for the Object class to get the signature for the equals and hashcode methods.
The HashMap class uses these methods to work with keys.
Add those two methods to your Key class.
For debugging, add println() statements to both of those classes to see when they are called and what the args are that are being passed to them.
For the guts of equals, its up to you to determine when two objects are equal.
For the hashcode, I'm not sure what needs to be there. What does the API doc in the Object class suggest?
Similar Threads
-
How to Run HelloWorld program?
By siji44 in forum New To JavaReplies: 8Last Post: 03-24-2010, 08:09 AM -
HelloWorld in EJB!
By bdtagar in forum Enterprise JavaBeans (EJB)Replies: 1Last Post: 01-04-2010, 11:55 AM -
Struts2 helloworld application.
By makpandian in forum New To JavaReplies: 0Last Post: 06-02-2009, 11:19 AM -
About Java HelloWorld
By Dankydoo in forum New To JavaReplies: 0Last Post: 01-11-2009, 10:08 PM -
Run a helloWorld in NetBeans
By mathias in forum NetBeansReplies: 1Last Post: 08-07-2007, 01:16 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks