views:

1255

answers:

3

Hello there,

I'm having trouble working out how to count instances of Values in a HashMap. I have seen that there is methods attached to the Object class that look as if they are able to help me, so I've tried to cast those in to work but I must be doing something wrong somewhere.

If there's an easier way, I haven't found it yet. NB: Library is my HashMap.

public void borrowBooks(String id, String name, String sid, String sname) {
 if((getKeyFromValue(Books, name).equals(id))&&(getKeyFromValue(Students, sname).equals(sid))){
  if((Object)Library.countValues(sid)!=5){
   Library.put(id, sid);
  }
  else{
   System.out.println("You have exceeded your quota. Return a book before you take one out." );
  }
 }
}
+3  A: 

Which doc are you looking at ? The Javadoc for Hashmap doesn't specify a countValues() method.

I think you want a HashMap<String, List<String>> so you store a list of books per student (if I'm reading your code correctly).

You'll have to create a list per student and put that into the HashMap, but then you can simply count the entries in the List using List.size().

e.g.

if (Library.get(id) == null) {
   Library.put(id, new ArrayList<String>());
}
List<String> books = Library.get(id);
int number = books.size() // gives you the size

Ignoring threading etc.

Brian Agnew
+2  A: 

First: There is (almost) no point in ever casting anything to Object. Since everything extends Object, you can always access the methods without casting.

Second: The way you're casting actually casts the return value, not the Library. If you were doing a cast that was really necessary, you would need an extra set of parentheses:

if(((Object)Library).countValues(sid) != 5)

Third: There is no countValues method in either HashMap or Object. You'll have to make your own.

This is the general algorithm to use (I'm hesitant to post code because this looks like homework):

initialize count to 0
for each entry in Library:
    if the value is what you want:
        increment the count
Michael Myers
A: 
int count = 0;

for(String str : Library.values())
{
    if(str == sid)
        count++;
    if(count == 5)
        break;
}

if(count < 5)
    Library.put(id, sid);
else
    System.out.println("You have exceeded your quota. Return a book before you take one out." );
MStodd