Solved

Can someone help me with this phonebook class?

Posted on 2011-09-15
28
419 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
ID: 36545725
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
ID: 36545777
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
ID: 36545778
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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 47

Expert Comment

by:for_yan
ID: 36545791
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
ID: 36545795
Try to write it yourseldf - I'll chek it
0
 

Author Comment

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

Expert Comment

by:for_yan
ID: 36545829
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
ID: 36545912
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
ID: 36545986
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
ID: 36546698
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
ID: 36546708
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
ID: 36546710


    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
ID: 36546786
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
 
LVL 47

Expert Comment

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

Author Comment

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

Expert Comment

by:for_yan
ID: 36546820

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
ID: 36547455
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
ID: 36547491
You need size() but not get(size())


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

Expert Comment

by:CEHJ
ID: 36548698
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
ID: 36549758

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
ID: 36550002
Thank you for all your help. How do I combine them?
0
 
LVL 47

Expert Comment

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

Author Comment

by:ryanbecker24
ID: 36550107
Ok
0
 

Author Closing Comment

by:ryanbecker24
ID: 36550117
Thanks
0
 
LVL 86

Expert Comment

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

Essentially they are identical
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36550152
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
ID: 36550168
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
egit plugin on eclipse 8 63
tomcat not starting 6 45
MySqlDump not dumping triggers 1 31
Delphi: barcode reading on android platform 1 30
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

777 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