0

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

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?

Ganesh
  • 5,977
  • 5
  • 19
  • 25
  • Well they do different things. One modifies an existing collection, with the parameter as an independent collection, whereas the other is just a straight assignment, copying the reference from the parameter to the field. – Jon Skeet Aug 16 '16 at 05:34
  • I meant in terms of efficiency the first one iterates over the collection.Why Downvote? – Ganesh Aug 16 '16 at 05:50
  • Downvoted because it's a very bad question - you've basically asked "Which is better, an apple or an orange?" You don't mention efficiency anywhere in the question, yet suddenly that's what you're asking about? – Jon Skeet Aug 16 '16 at 05:54
  • Well I am new to stackoverflow. I might not have framed the question correctly you could have asked in comments. But downvoting is not the way to do it. – Ganesh Aug 16 '16 at 05:55
  • 2
    If you're new to Stack Overflow, you may want to consider that you're not in the best position to tell others how they should behave on Stack Overflow. If you ask a bad question, you should expect it to be downvoted... that's the way SO works. You should probably read https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ – Jon Skeet Aug 16 '16 at 05:56

1 Answers1

2

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875