Set.clear()和Set.addAll()vs Assignment哪个更好? [重复]

时间:2021-02-23 09:27:29

This question already has an answer here:

这个问题在这里已有答案:

Which of the following should be followed while setting Set elements and why?

设置Set元素时应遵循以下哪项,为什么?

private Set<TestDetailEntity> testDetails = new HashSet<>();

public void setTestDetails(Set<TestDetailEntity> testDetails) {
        this.testDetails.clear();
        this.testDetails.addAll(testDetails);
    }


public void setTestDetails(Set<TestDetailEntity> testDetails) {
        this.testDetails = testDetails;
    }

The first one iterates over the collection. What I am trying to ask here is which one is efficient way?

第一个迭代集合。我在这里要问的是哪一个是有效的方法?

1 个解决方案

#1


1  

It completely depends on your goal.

这完全取决于你的目标。

The first takes a copy of the contents of the set.

第一个获取集合内容的副本。

The second keeps a reference to the set passed in, which is shared with the calling code.

第二个保留对传入的集合的引用,该集合与调用代码共享。

Neither is preferred in the absense of more design constraints, although if setTestDetails is going to keep a reference to the passed-in set, that should be clearly documented. (Actually, it should be clearly documented either way.)

在没有更多设计约束的情况下,两者都不是首选,尽管如果setTestDetails将保留对传入集的引用,那么应该清楚地记录。 (实际上,无论哪种方式都应该清楚记录。)

#1


1  

It completely depends on your goal.

这完全取决于你的目标。

The first takes a copy of the contents of the set.

第一个获取集合内容的副本。

The second keeps a reference to the set passed in, which is shared with the calling code.

第二个保留对传入的集合的引用,该集合与调用代码共享。

Neither is preferred in the absense of more design constraints, although if setTestDetails is going to keep a reference to the passed-in set, that should be clearly documented. (Actually, it should be clearly documented either way.)

在没有更多设计约束的情况下,两者都不是首选,尽管如果setTestDetails将保留对传入集的引用,那么应该清楚地记录。 (实际上,无论哪种方式都应该清楚记录。)