java - Should I use .clone() in the constructor? -


for example, should use:

public line(vector dorigin, vector ddir)  {     origin = dorigin.clone();      dir = ddir.clone(); }  

instead of:

public line(vector dorigin, vector ddir)  {      origin = dorigin;       dir = ddir; } 

???

so, suppose have program this: line[] line = new line[10];

for (i = 0; < n; i++) {     vector temp = new vector(i, 0);     line[i] = new line(temp, temp); } //and operate on array line 

then should use first constructor?

clone() often regarded broken, , rather code constructors explicitly (or delegate construction method, can't make use of final enforce immutability easily).

to address edited question, constructor need copies of passed entities, rather references original parameters ? if you're passing collection in, may need take copy of collection , possibly entities contained within collection (that may or may not possible depending on entity's implementation). of course, if original entities immutable doesn't matter , can pass references impunity. may still worry copying collection, however,such external party doesn't change collection (re-orders, adds, removes etc.)

who owns data ? key question here.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -