java - Why answer is coming as 2:2:1:1 when we are removing all elements of a SET -
when add elements in set,it discard duplicate values.when removing elements of set k1 , k2. still final size 1. answer of code 2:2:1:1.
class keymaster { public int i; public keymaster(int i) { this.i = i; } public boolean equals(object o) { return == ((keymaster) o).i; } public int hashcode() { return i; } } public class mapit { public static void main(string[] args) { set<keymaster> set = new hashset<keymaster>(); keymaster k1 = new keymaster(1); keymaster k2 = new keymaster(2); set.add(k1); set.add(k1); set.add(k2); set.add(k2); system.out.print(set.size() + ":"); k2.i = 1; system.out.print(set.size() + ":"); set.remove(k1); system.out.print(set.size() + ":"); set.remove(k2); system.out.print(set.size()); } }
this because key in hashset not immutable when change field value of k2
, field value changed object remain same, when want remove k2
set, cant find k2 because object have been changed.
for understanding better let k1
go , test this:
class mapit { public static void main(string[] args) { set<keymaster> set = new hashset<keymaster>(); keymaster k2 = new keymaster(2); set.add(k2); set.add(k2); system.out.print(set.size() + ":"); k2.i = 3; system.out.print(set.size() + ":"); set.remove(k2); system.out.println(set.size()); } }
Comments
Post a Comment