简体   繁体   English

将对象转换为HashMap

[英]Casting a Object to HashMap

I'm having trouble working out how to count instances of Values in a HashMap. 我在解决如何计算HashMap中的Value实例时遇到麻烦。 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. 我已经看到Object类上有附加的方法,看起来好像它们可以为我提供帮助,因此我尝试将它们强制转换为起作用,但是我必须在某处做错了什么。

If there's an easier way, I haven't found it yet. 如果有更简单的方法,我还没有找到。 NB: Library is my HashMap. 注意:图书馆是我的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." );
        }
    }
}

Which doc are you looking at ? 您要看哪个文件? The Javadoc for Hashmap doesn't specify a countValues() method. Hashmap的Javadoc没有指定countValues()方法。

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

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(). 您必须为每个学生创建一个列表,然后将其放入HashMap,但是您可以使用List.size()简单地计算列表中的条目。

eg 例如

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. 忽略线程等

First: There is ( almost ) no point in ever casting anything to Object . 第一: 几乎没有任何意义向Object投任何东西。 Since everything extends Object , you can always access the methods without casting. 由于所有内容都扩展了Object ,因此您始终可以在不强制转换的情况下访问方法。

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 . 第三: HashMapObject中都没有countValues方法。 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
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." );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM