您好我不知道如何实际查找但我很好奇,您可以根据您在构造函数中提供的参数更改对象。就像你有一个对象库,它有一个构造函数public Library(Map books)之类的东西。如果我创建Map ... new Hashmap,在其中放入5个键值,然后将该映射提供给Library的构造函数,则Library对象将具有一个包含5个键值的hashmap。如果我在hashmap中再插入2个键值会发生什么?构建的Library对象突然在其地图中有7个键值,还是只有最初的5个?
答案 0 :(得分:1)
这取决于构造函数的作用。如果构造函数只将Map存储在实例变量中:
public class Library {
private final Map<String, String> books;
public Library(Map<String, String> books) {
this.books = books;
}
public int size() {
return books.size();
}
public static void main(String[] args) {
Map<String, String> myBooks = new HashMap<String,String>();
myBooks.put("Jonathan Swift", "Gullivers Travels");
myBooks.put("Robert Louis Stevenson", "Treasure Island");
myBooks.put("William Shakespeare", "Hamlet");
myBooks.put("J R R Tolkein", "The Hobbit");
myBooks.put("Mary Shelley", "Frankenstein");
Library library = new Library(myBooks);
myBooks.put("J K Rowling", "Harry Potter and the Philosophers stone");
System.out.println("Library contains" + library.size() + " books");
}
}
然后,Library包含对传递给它的地图的引用,它将看到对该地图内容的任何更改。上面的代码应该打印出库中有6本书。
另一方面,如果构造函数制作了地图的副本:
public class Library {
private final Map<String, String> books;
public Library(Map<String, String> books) {
this.books = new HashMap<String, String>(books);
}
public int size() {
return books.size();
}
public static void main(String[] args) {
Map<String, String> myBooks = new HashMap<String,String>();
myBooks.put("Jonathan Swift", "Gullivers Travels");
myBooks.put("Robert Louis Stevenson", "Treasure Island");
myBooks.put("William Shakespeare", "Hamlet");
myBooks.put("J R R Tolkein", "The Hobbit");
myBooks.put("Mary Shelley", "Frankenstein");
Library library = new Library(myBooks);
myBooks.put("J K Rowling", "Harry Potter and the Philosophers stone");
System.out.println("Library contains" + library.size() + " books");
}
}
然后Library有自己的地图副本,并且不会看到对原始地图的任何更改,因此上面的代码应该打印出库中有5本书。
答案 1 :(得分:0)
是的,它会的。例如:
import java.util.Map;
import java.util.HashMap;
public class HelloWorld{
public static void main(String []args){
Map<String, String> books = new HashMap();
books.put("Author1", "Book1");
books.put("Author2", "Book1");
Library l1 = new Library(books);
books.put("Author3", "Book1");
System.out.println(l1.toString());
}
}
class Library {
private Map<String, String> books;
public Library(Map<String, String> books) {
this.books = books;
}
@Override
public String toString() {
return books.toString();
}
}
输出将是: {Author3 = Book1,Author2 = Book1,Author1 = Book1}
这是因为java不是将对象本身传递给构造函数,而是传递给该对象。这意味着从主要方法书籍地图和图书馆书籍地图实际上是一个对象。 如果您不希望Library类从Library类外部更改,则可以根据构造函数输入创建新对象。说谎:
public Library(Map<String, String> books) {
this.books = new HashMap(books);
}