[英]What is the difference between assignment operator and addAll in java?
I wondered related to a book question in a set chapter?我想知道与固定章节中的书本问题有关吗?
Set<String> mySet = new HashSet<>();
mySet.add("red");
mySet.add("blue");
mySet.add("pink");
mySet.add("black");
//first presentation
Set<String> newSetFirst = new HashSet<>();
newSetSirst.addAll(mySet);
//second presentation
Set<String> newSetTwo;
newSetTwo = mySet;
what difference between first presentation and second presentation?第一次演讲和第二次演讲有什么区别?
What mean of newSetSirst.addAll(mySet)? newSetSirst.addAll(mySet) 是什么意思?
What mean of newSetTwo = mySet? newSetTwo = mySet 是什么意思?
First presentation:第一次介绍:
Set<String> newSetFirst = new HashSet<>();
newSetFirst.addAll(mySet);
System.out.println(newSetFirst); // Prints ["red", "blue", "pink", "black"]
mySet.clear();
System.out.println(newSetFirst); // Prints ["red", "blue", "pink", "black"]
When you addAll
, you're just adding everything to an existing set.当您
addAll
时,您只是将所有内容添加到现有集合中。 Updates to the set you added from aren't reflected in that set, because it's entirely separate.对您添加的集合的更新不会反映在该集合中,因为它是完全独立的。
Second presentation:第二个介绍:
Set<String> newSetTwo;
newSetTwo = mySet;
System.out.println(newSetTwo); // Prints ["red", "blue", "pink", "black"]
mySet.clear();
System.out.println(newSetTwo); // Prints []
When you assign, you're just giving yourself another variable which points to the same list.当你分配时,你只是给自己另一个指向同一个列表的变量。
mySet == newSetTwo
is true: there's only one set. mySet == newSetTwo
为真:只有一组。 As such, changing mySet
changes newSetTwo
as well.因此,更改
mySet
更改newSetTwo
。
First presentation creates a new list and adds every item to it from the first list.第一个演示文稿创建一个新列表并将第一个列表中的每个项目添加到其中。 If you change one item in the mySetFirst list, the mySet list is not gonna be changed.
如果您更改 mySetFirst 列表中的一项,则 mySet 列表不会更改。
The second presentation points to the reference of mySet.第二个表示指向 mySet 的引用。 If you change one item in newSetTwo, the item is gonna get changed in mySet too.
如果您更改 newSetTwo 中的一项,则该项目也会在 mySet 中更改。 In that case mySet and newSetTwo are the same list.
在这种情况下, mySet 和 newSetTwo 是同一个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.