为什么我在同一个Map对象上有两个引用?

时间:2015-03-19 19:51:58

标签: java dictionary reference mutable

doSomething 方法中,我创建了一个新的User对象Map。我已经在书籍列表中添加了一本新书,并为用户设置了新名称。当我调用此方法时,会更改用户用户的原始地图。为什么呢?

Book.java

public class Book {

    private String name;

    public Book() {
    }
    //getters and setters
}

User.java

public class User {

    private String firstName;
    private String lastName;
    private List<Book> listOfBooks;

    public User() {
    }

    public User(String firstName, String lastName, List<Book> listOfBooks) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.listOfBooks = listOfBooks;
    }
    //getters and setters
}

ListOfBook.java

public class ListOfBook {

private final List<Book> books;

public ListOfBook() {
    books = new ArrayList<>();
    books.add(new Book("The Lord of the Rings"));
    books.add(new Book("The Little Prince"));
}

public List<Book> getBooks() {
    return books;
    }
}

ListOfUser.java

public class ListOfUsers {

    private static ListOfUsers instance;
    private final Map<String, User> users;

    ListOfBook books = new ListOfBook();

    private ListOfUsers() {
        users = new LinkedHashMap<>();
        users.put("1", new User("X", "Y", books.getBooks()));
        users.put("2", new User("Z", "N", books.getBooks()));
    }

    public static ListOfUsers getInstance() {
        if (instance == null) {
            instance = new ListOfUsers();
        }
        return instance;
    }

    public Map<String, User> getUsers() {
        return users;
    }
}

Controller.java

public class Controller {

    private final Map<String, User> users;

    public Controller() {
        users = ListOfUsers.getInstance().getUsers();
    }

    public void doSomething() {
        Map<String, User> newUsers = new LinkedHashMap<>();
        newUsers.putAll(users);
        printUsers(users);
        User user = newUsers.get("1");
        List<Book> listOfBooks = user.getListOfBooks();
        listOfBooks.add(new Book("The Da Vinci Code"));
        user.setFirstName("N.N.");
    }

    public static void printUsers(Map<String, User> users) {
        for (Map.Entry<String, User> user : users.entrySet()) {
            System.out.print(user.getValue().getFirstName() + " ");
        }
        System.out.println();
    }
}

main.java

public class Example {

    public static void main(String[] args) {
        Controller controller = new Controller();
        controller.doSomething();
        controller.doSomething();
        ListOfUsers listOfUsers = ListOfUsers.getInstance();
        Map<String, User> users = listOfUsers.getUsers();
        List<Book> listOfBooks = users.get("1").getListOfBooks();
        for (int i = 0; i < listOfBooks.size(); i++) {
            System.out.println(listOfBooks.get(i).getName());
        }
        Controller.printUsers(users);
    }
}

0 个答案:

没有答案