1

我无法弄清楚如何计算 HashMap 中的值实例。我已经看到 Object 类附加了一些方法,它们看起来好像可以帮助我,所以我试图将它们投入使用,但我一定在某处做错了。

如果有更简单的方法,我还没有找到。注意:图书馆是我的 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." );
        }
    }
}
4

3 回答 3

3

你在看哪个文档?Hashmap的Javadoc没有指定 countValues() 方法。

我认为您想要一个HashMap<String, List<String>>,因此您可以存储每个学生的书籍列表(如果我正确阅读了您的代码)。

您必须为每个学生创建一个列表并将其放入 HashMap,然后您可以使用 List.size() 简单地计算列表中的条目。

例如

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

忽略线程等。

于 2009-04-22T19:50:41.383 回答
3

第一:(几乎Object. 由于一切都 extends Object,您可以随时访问方法而无需强制转换。

第二:您投射的方式实际上是投射返回值,而不是库。如果你正在做一个真正必要的演员表,你将需要一组额外的括号:

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

第三: or中没有countValues方法。你必须自己做。HashMapObject

这是使用的一般算法(我很犹豫发布代码,因为这看起来像家庭作业):

initialize count to 0
for each entry in Library:
    if the value is what you want:
        increment the count
于 2009-04-22T19:54:32.480 回答
0
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." );
于 2009-04-22T20:00:22.843 回答