Solved

Can someone help me with this phonebook class?

Posted on 2011-09-15
28
416 Views
Last Modified: 2012-05-12
Hi, I have only used HashSets and HashMaps once before and I only used it with both Strings. I have never used it with a long before.
phonebook:

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

public PhoneBook()
{
phoneBook.put("Peter Griffin", 53154321945L);
phoneBook2.add(9084268675L);
}


/**
 * Method that takes two parameters the name and telephone number and then attempts to add information into the phonebook .
 * If the name is already in the phonebook then the method outputs an error message, display's already stored phone number that corresponds to the given name, and returns
 * false. Otherwise this method adds provided name/phone number info into the phonebook, displays phone info to all names that start with the same letter as provided name
 * and returns true
 */
public boolean addInformation(String name, long number)
{
if(!phoneBook.isEmpty()){
Long name2 = phoneBook.get("Peter Griffin");
System.out.println(number + "Error");
return false;
}
else if(phoneBook.isEmpty()){
phoneBook.put(name,number);
}
}
/**
 * Method which verifies that the phonebook contains only unique phone numbers. To implement this method use the following algorithm.
 * Create a HashSet of Long numbers
 * Copy all the phone numbers from the HashMap into created HashSet
 * If the sizes of the phonebook's HashMap and created HashSet are the same then return true, indicating that all the phone numbers are unique
 * Otherwise return false, indicating that there are duplicate phone entries.
 */
public boolean uniqueNumber()
{
   HashSet<Long> phoneBook2 = new HashSet<Long> ();
   phoneBook2 = phoneBook.clone();
    if(phoneBook.size()=phoneBook2)
    {
        return true;
    }
        else{
            return false;
        }
    }
}

0
Comment
Question by:ryanbecker24
  • 14
  • 10
  • 3
28 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
What you need in your method uniqueNumber is get all valuies from your hashmap
and create HasSet and add all the numbers to HashSet if the suize is the
same then all number s are unique
0
 

Author Comment

by:ryanbecker24
Comment Utility
Is there a specific method to get all values from hashmap and to add all numbers to HashSet?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
So you should take advantage of the fact that HashSet can have onlyuniuqe elements - when
it adds non-unique elelmnt it will ignore it

As opposed to other collections - say ArrayList which can have duoplicates - so you need to iterate
through all values in your hashmap and add them tho HashSet  and to ArrayList
and then compare the sizes - idf the size is the saem - the it was unique , if not - then it was not unique

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
No, I don'st think so, but there is a method map.keySet()
then you need to iterate though all keys, and get corresponding values and
add them to HashSet (sya PhoneBokok2)
and then actually you don't want ArrayLisrt -I was wriong - you just comaper sizes of phoneBook and phoneBook2
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Try to write it yourseldf - I'll chek it
0
 

Author Comment

by:ryanbecker24
Comment Utility
How do I copy phone numbers from HashMap to HashSet? Do I use that clone() method?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
By the way you also need to correct your adInformation method - otherwise
it does not compaile as you have to hae a retutn m,ethod in all cases:
public boolean addInformation(String name, long number)
{
if(!phoneBook.isEmpty()){
Long name2 = phoneBook.get("Peter Griffin");
System.out.println(number + "Error");
return false;
}
else if(phoneBook.isEmpty()){
phoneBook.put(name,number);
  
}
return true;  
}

Open in new window

0
 

Author Comment

by:ryanbecker24
Comment Utility
This is what I have. I don't think its right at all
public boolean uniqueNumber()
{
   HashSet<Long> phoneBook2 = new HashSet<Long>();
   phoneBook2 = phoneBook.clone();
    for(String phoneBook : phoneBook2.keySet())
    {
        if(phoneBook.size()=phoneBook2.size()){
        return true;
    }
    }
        else{
            return false;
        }
    }
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
No this is not right.
One thing is that you don;'t need any clone()

And your phoneBook and phoneBook2 are different animals
phoneBook is a map - name vs number

phoneBook2 ness to be a set - just a set of numbers

phoneBook2 does not exoist at the beginning - just create empty hashset named PhoneBook2 - that part is right


Then you should get your keys friom existing HashMap (phoneBook) -
but better do it befoer the loop
like
Set set = phoneBook.keySet();
(not friom phoneBook2 - that one is empty at this time -  from phoneBook)

then you need to iterate through those keys - and for each key - you should get the vlaue

(ther is a method get(String) in your hasmap and only values should be added to your HashSet (phoneBook2))

after travesrsing through all keys (and so through all values) yiou need to compare the sizes
of hashmap and hashset
(hashmap is  a map, hashset is a set - so they are really dieffernt,
but ther sizes in both cases are numbers of elements - so the sizes can be compared,
although in hashmap each element is a map.entry and in hashset each element is just
a long value, but numbers of element can be compared)

Thisnk about all of it and try again
0
 

Author Comment

by:ryanbecker24
Comment Utility
Am I getting closer?

public void uniqueNumber()
{
   HashSet<Long> phoneBook2 = new HashSet<Long>();
   Set set = phoneBook.keySet();
    for(String phoneBook : phoneBook2)
    {
        phoneBook2.get(size());
        phoneBook.get(size());
    }
       if(phoneBook2.get(size())=phoneBook.get(size())){
           return true;
           else{
               return false;
            }
        }
    }
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Well, maybe a little bit

this part is right:
  HashSet<Long> phoneBook2 = new HashSet<Long>();
   Set set = phoneBook.keySet();

But then you need to go through all keys of you HashMap, thorough your set obect (of Type Set)
and for exach key find the value

It should start like that:

    for(String s : set){
// and here for each s you should get youer value and add it to your new collection phoneBook2

}

and then when you are  done you can compare sizes,

but rememeber that comparioson oerator in Java is not "=" but "=="

OK, do it again now





0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility


    for(String s : set){
// and here for each s you should get your value and add the vlaue to your new collection of type HashSet, which is  phoneBook2

}

0
 

Author Comment

by:ryanbecker24
Comment Utility
Is the inside of the loop right and the if statement?

public boolean uniqueNumber()
{
   HashSet<Long> phoneBook2 = new HashSet<Long>();
   Set set = phoneBook.keySet();
    for(String s : set)
    {
        s.get(set);
        s.add(phoneBook2);
    }
       if(phoneBook2.get(size())== phoneBook.get(size())){
           return true;
           else{
               return false;
            }
        }
    }
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 47

Expert Comment

by:for_yan
Comment Utility
you cannot add HashSet (PhoneBook2) to String, you can add String to set, but not vice versa
0
 

Author Comment

by:ryanbecker24
Comment Utility
So, are you saying that it would be s.get(phoneBook2) and s.add(set).
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

how can you get(PhoneBook) from object s, when s represents a String ?

how can you add set to String ? String does not have such methods

This is how it should be:

for(String s : set)
    {
   Long lng = phoneBook.get(s); // this way you get the number as a Long object for the key in from your HashMap (from phoneBook)
        phoneBook2.add(lng);  // this way you add this object to your HashSet  (to phoneBook2) (it will add only if there is no such number already
   
    }
0
 

Author Comment

by:ryanbecker24
Comment Utility
For the if statement do I still need to call the size() method or do I compare Ing and set.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You need size() but not get(size())


 if(phoneBook2.size()== phoneBook.size()){
....
}
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
This question is a duplicate of http://www.experts-exchange.com/Programming/Languages/Java/Q_27310501.html and should be deleted/combined
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility

even though I believe we went through a very good exercise, it also can be done easier
using values(), rather than keySet()  method

this is an example, please let me know if you have any questions:
   HashMap<String, Long>  phoneBook =  new HashMap<String, Long>();
            phoneBook.put("a",20L);
          phoneBook.put("b",30L);
          phoneBook.put("c",40L);
          phoneBook.put("d",20L);

        HashSet<Long> phoneBook2 = new HashSet<Long>();

           phoneBook2.addAll(phoneBook.values());

        if(phoneBook2.size() != phoneBook.size())System.out.println("not unique");
        else System.out.println("unique");

Open in new window


Output:
not unique

Open in new window

0
 

Author Comment

by:ryanbecker24
Comment Utility
Thank you for all your help. How do I combine them?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
They are different questions - don't need to be combined
0
 

Author Comment

by:ryanbecker24
Comment Utility
Ok
0
 

Author Closing Comment

by:ryanbecker24
Comment Utility
Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>They are different questions - don't need to be combined

Essentially they are identical
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
No, one was asking how to put Long numbers to HashMap, another one was about specifics of HashMap vs HashSet and the code - they are different .
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
It's rather academic anyway really since as i said in the earlier question, using Long for a phone number is simply wrong
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
noX challenge 17 75
mapAB Challlenge 35 84
JDeveloper 12c for 32 bit 4 34
advertisement module in core php 4 79
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now