Reputation: 772
I have an ArrayList
that has some objects that I defined in it. Based on some criteria, I want to copy some of the objects from the first list to the second list (which starts empty), but these objects that I copy could be copied several times ( can be duplicates ).
To simplify for an example let's say my second list contains only 2 objects that are duplicates. Objects a and b.
If I modify something in object a, will that modification also appear on object b ? It is just a reference that is passed or it's a copy of an object?
for( int i = 0; i < Selected.size(); i++)
{
double chance = random.nextInt(100);
chance = chance/100;
if( chance >= constCrossover )
{
Cross.add(Selected.get(i));
//here i add items that might be duplicates
}
}
I will make further modifications in the Cross list and i don't want duplicate objects to interact with eachcother.
Upvotes: 1
Views: 366
Reputation: 472
It will be a reference so changes in one will be visible in the other. You'd have to
I think it's better to use the foreach
mode of for-loop in Java.
for (YourObject yourObject : selected) {
if(yourObjectShouldBeAdded) {
cross.add(new YourObject(yourObject)); //initialize new copy in any way needed
}
}
Another alternative is to use Guava libraries: Lists and Iterables. In this way:
List<YourObject> cross = Lists.newArrayList(Iterables.filter(selected, new Predicate<YourObject>() {
@Override
public boolean apply(YourObject input) {
if(yourObjectShouldBeAdded) {
return true;
}
}
}));
I think in your case, the condition yourObjectShouldBeAdded
refers to a random number chance
being greater than a constant constCrossover
. You can simply substitute that.
Upvotes: 0
Reputation: 21
It is always a reference that is copied to the new array list, to avoid this implement clone in your object and in the second arraylist add the cloned object.
Upvotes: 2
Reputation: 36304
dont look at objects.. look at references.. if both "a" and "b" references point to the same object, then if you change the object via "a", then when "b" accesses it, the changes made by "a" can be seen..
Upvotes: 1
Reputation: 16476
Yes, changes to a single object in the second list will be reflected on all of it's duplicates. To avoid this you might need to clone your object, i.e. via a copy constructor.
Upvotes: 2
Reputation: 1500185
It's always a reference. The value of an expression, the value in an array etc is always either a reference or a primitive value. Nothing will copy an object implicitly - you'd have to do that explicitly.
(As an aside, you should follow Java naming conventions - Selected
and Cross
should probably be selected
and cross
.)
Upvotes: 7