0

if I want "id" is key and "name", "phoneNumber", "eamil" are values.

public class Personal {
 private int id;
 private String name;
 private int phoneNumber;
 private String email;
 public Personal(int id){
 this.id = id;
 }
 //getter and setter here
}

after input many person data. I can get data by id.

output ex: map.get(100001); // [Dan, 123456, [email protected]]
 map.get(100002); // [Kim, 123343, [email protected]] 
 ...

Question: What's the best ways to implement this HashMap ?

Thanks a lot!

asked Dec 17, 2012 at 14:10
2
  • 3
    What's wrong with using HashMap<Integer, Personal>, and putting your instances of Personal class into the map? Commented Dec 17, 2012 at 14:12
  • Just a little be confuse, I think I already get a answer. THANKS :) Commented Dec 17, 2012 at 15:03

1 Answer 1

8

If the IDs are unique and set in stone, you could use:

Map<Integer,Personal> map = new HashMap<Integer,Personal>();

To add an object p:

map.put(p.getId(), p);

Then

map.get(100001);

would return the corresponding object.

If the IDs can repeat or can change, things get more complicated. If that's the case, please explain your exact requirements so that we can help further.

answered Dec 17, 2012 at 14:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.