android - Creating new Object from existing object, how to make them independent - java -
i don't understand why following code not working. trying create new object using existing object elements, , process new object change elements. in end both objects changed. doing wrong?
contours = new arraylist<matofpoint>(); hierarchy = new mat(); //find contours of filtered image using opencv findcontours function imgproc.findcontours(mfilteredframenoholes, contours, hierarchy , imgproc.retr_external, imgproc.chain_approx_simple); //aproximate contours aproximatedcontours = new arraylist<matofpoint>(contours); //aproximatedcontours = (arraylist<matofpoint>) contours.clone(); //aproximatedcontours.addall(contours); aproximatedcontours.dosomeoperations()
because aproximatedcontours
, contours
have same element references.
aproximatedcontours = new arraylist<matofpoint>(contours);
simply creates new list same elements in contours , if these elements mutated
effects reflected in list too.
usually bad idea toss around shared mutable objects this, unless know side effects. following example demonstrates behavior:
class foo{ int val; foo(int x){ val = x; } void changeval(int x){ val = x; } public static void main(string[] args) { foo f = new foo(5); list<foo> first = new arraylist<foo>(); first.add(f); list<foo> second = new arraylist<foo>(first); system.out.println(first.get(0).val);//prints 5 second.get(0).changeval(9); system.out.println(first.get(0).val);//prints 9 } }
Comments
Post a Comment