[英]What is the behavior of a TreeMap instance passed into a constructor following changes in main method
Suppose I have the setup: 假设我有安装程序:
TreeMap<Long,ClassA> derkMap = new TreeMap<Long,ClassA>();
derkMap.put(1L,new ClassA());
Note that ClassA
has public void doSomething()
, which when called will change the instance's state permanently (in what precise way is irrelevant to this question). 请注意, ClassA
具有public void doSomething()
,当调用它时,它将永久更改实例的状态(以哪种确切方式与该问题无关)。 Note that once doSomething()
is called, ClassA
has a public boolean hasItBeenCalled()
which will return true
; 请注意,一旦调用doSomething()
, ClassA
具有一个public boolean hasItBeenCalled()
,该public boolean hasItBeenCalled()
将返回true
; else it'll return false
if doSomething()
has not been called. 否则,如果未调用doSomething()
它将返回false
。
If I run the following sequence in my main method: 如果我在主方法中运行以下序列:
derkMap
instance to constructor of some ClassB
(ie instantiate in my main method ClassB objectB = new ClassB(derkMap);
). (1)将derkMap
实例传递给某个ClassB
构造函数(即在我的主要方法ClassB objectB = new ClassB(derkMap);
实例化ClassB objectB = new ClassB(derkMap);
)。 derkMap.get(1L).doSomething();
(2)调用derkMap.get(1L).doSomething();
from main method. 从主要方法。 ClassB
(ie, objectB
), try derkMap.get(1L).hasItBeenCalled()
. (3) 在 ClassB
实例(即objectB
)内,尝试derkMap.get(1L).hasItBeenCalled()
。 Will (3) return true
or false
? (3)会返回true
还是false
?
Everything in Java is pass by value. Java中的一切都是通过价值传递的。 Recommended reading: this and its follow up . 推荐读物: 这 及其后续内容 。
Edit: even more recommended reading: Is Java "pass-by-reference" or "pass-by-value"? 编辑:甚至推荐阅读: Java是“按引用传递”还是“按值传递”?
Another edit: This answer no longer makes sense as the question was edited, but I'm leaving it because I think it's what the OP is actually confused about. 另一个编辑:这个问题在编辑问题时不再有意义,但我将其保留,因为我认为这是OP真正困惑的地方。
It should return true. 它应该返回true。 That's because when you pass map as a parameter of classB its reference is copied by value and it still points to the original map. 这是因为当您将map作为classB的参数传递时,其引用将按值复制,并且仍指向原始地图。 If you call methods of the element inside map it still executes those methods on the orginal map. 如果您在map内部调用元素的方法,它仍会在原始地图上执行这些方法。
EDIT 编辑
By the way, after I answered this question it took me 3 minutes to verify it by writing sample code. 顺便说一句,在我回答了这个问题之后,我花了3分钟时间通过编写示例代码进行验证。 I'm just wondering why you haven't tried it yourself. 我只是想知道为什么您自己还没有尝试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.