Link to home
Start Free TrialLog in
Avatar of ryanbecker24
ryanbecker24

asked on

How do you use long in a HashMap?

I am trying to use long instead of integer to create a phoneBook. It keeps saying its an integer and its to large.

import java.util.HashSet;
import java.util.HashMap;
/**
 * Write a description of class MapTester here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class PhoneBook
{
private HashMap<String, Long> phoneBook = new HashMap<String, Long> ();
private HashSet<String, Long> phoneBook = new HashSet<String, Long>();

public PhoneBook()
{
phoneBook.put("Homer Jay Simpson", 53193924587);
phoneBook.put("Peter Griffin", 53154321945);
phoneBook.put("Apu Nahasapeemapetilon", 53142344418);
}


/**
 * Method that takes two parameters the name and telephone number and then attempts to add information into the phonebook
 */
public void phoneBook(String name, long number)

{
if(phoneBook.put(name, number);
}


public String lookupNumber(String name)

{
return phoneBook.get(name);
}
}
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
phoneBook.put("Homer Jay Simpson", 53193924587L);
Otherwise it does not know that it is long
Avatar of ryanbecker24
ryanbecker24

ASKER

Ok thanks
Avatar of Gurvinder Pal Singh
how about this

phoneBook.put("Apu Nahasapeemapetilon", new Long(53142344418));
with autoboxing you don't need to create new Long(...), as soon as compiler understands
that you are providing long number and for that you need to add "L" or "l"
In general if you write numeber without decimal point Java will treat it as integer, untill you add "L" or "l" to it
A phone number is not an integral value - it's a String, so you need Map<String, String>
For a more durable design, you need something other than someone's name as the key in your Map, or the phone book will break if you have duplicate names
It is best to initialize Long class with given integer.