Comparing sets in Java; operation does not work as expected in both directions -


having created 2 sets of different sizes, common elements, intention identify elements in each set make different other set. set class in java seemed have method: removeall. did following:

import java.util.*;  public class helloworld {      @suppresswarnings("unchecked")     public static void main(string args[]) {          // create new set         set<string> myset1 = new hashset();          // add elements         myset1.add("1");         myset1.add("2");         myset1.add("4");         myset1.add("5");         myset1.add("6");         myset1.add("7");          // print elements of set1         system.out.println("myset1: " + myset1);          // create new set         set<string> myset2 = new hashset();          // add elements         myset2.add("1");         myset2.add("2");         myset2.add("3");         myset2.add("5");         myset2.add("6");         myset2.add("7");         myset2.add("8");          system.out.println("myset2: " + myset2);          // compare 2 sets         system.out.println("myset1 matches myset2: " + myset1.equals(myset2));          // remove elements of myset2 myset1         set<string> deletions = myset1;         deletions.removeall(myset2);         system.out.println("deletions: " + deletions);          // remove elements of myset1 myset2         set<string> updates = myset2;         updates.removeall(myset1);         system.out.println("updates: " + updates);     } } 

the result is:

myset1: [1, 2, 4, 5, 6, 7] myset2: [1, 2, 3, 5, 6, 7, 8] myset1 matches myset2: false deletions: [4] updates: [1, 2, 3, 5, 6, 7, 8] 

why isn't result 'updates' [3,8]?

deletions refers same set myset1 due set<string> deletions = myset1 assignment. therefore deletions.removeall removed elements original set myset1, second removeall received set contains "4".

you should create copies of original sets in order not mutate myset1 , myset2 :

set<string> deletions = new hashset<>(myset1); // create copy of myset1 deletions.removeall(myset2); system.out.println("deletions: " + deletions);  // remove elements of myset1 myset2 set<string> updates = new hashset<>(myset2); // create copy of myset2 updates.removeall(myset1); system.out.println("updates: " + updates); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -