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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -