简体   繁体   English

如何使用对象作为值构成HashMap,而对象又具有它自己的HashMap。 爪哇

[英]How to make HashMap with an object as value, which again have it's own HashMap of objects. Java

I have been working on this problem for quite some time now, searching around the internet to see if there was any answers, but to no luck unfortunately. 我已经在这个问题上研究了很长时间了,在互联网上搜索以查看是否有任何答案,但是不幸的是没有运气。

As the title says I am trying to make a HashMap which uses an Object (another class) as a value. 如标题所述,我正在尝试制作一个使用Object (另一个类)作为值的HashMap Then, I want that Object , to hold another HashMap inside it self which also uses another Object as a value. 然后,我希望该Object可以在其自身内部保存另一个HashMap ,它也使用另一个Object作为值。

Here is how I would have done it: 这是我应该做的:

BookAdmin.java BookAdmin.java

import java.util.HashMap;

public class BookAdmin
{
    private static HashMap<String, Customer> customer = new Customer<String, Customer>();

    public static void main(String [] args)
    {
        customer.put("James", new Customer("James"));
        customer.put("Peter", new Customer("Peter"));

        customer.get("James").newBook("Flying 101");

        customer.get("James").seeBooks();
    }
}

Customer.java 客户.java

import java.util.HashMap;

public class Customer
{
    private static HashMap<String, Book> book = new Book<String, Book>();
    private static String name = "";

    public Customer (String nameIn)
    {
        name = nameIn;
    }

    public void newBook (String title)
    {
        book.put(title, new Book(title));
    }

    public void seeBooks()
    {
        for (String l: book.keySet())
        {
            System.out.println(book.get(l).toString());
        }
    }
}

Book.java Book.java

public class Book
{
    private static String title = "";

    public Book (String titleIn)
    {
        title = titleIn;
    }

    public String toString()
    {
         return title;
    }
}

So it would seem to be pretty alright, but if I check "Peter"'s books too, it shows that he too owns "Flying 101". 因此,这似乎还不错,但是如果我也查看“彼得”的书,则表明他也拥有“飞行101”。 It's like they share the same book hashmap. 就像他们共享同一本书的哈希图一样。

The cause for that issue is that you maintain your map in a static context. 该问题的原因是您在静态上下文中维护地图。 This means the map is shared across all instances of a class, see also JLS 8.3.1.1. 这意味着该映射一个类的所有实例之间共享 ,另请参见JLS 8.3.1.1。 - static Fields -静态字段

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. 如果将一个字段声明为静态,则无论该类最终会创建多少实例(可能为零),都只存在该字段的一个具体化身。

So when you say "It's like they share the same book hashmap.", that is because they actually do :) 因此,当您说“就像他们共享同一本书的哈希图。”时,这是因为他们实际上在做:)

Remove all the static modifiers from the posted code and you should be good to go 从发布的代码中删除所有静态修饰符,您应该一切顺利

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

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