collections - Updating the objects of a Set in Java -


i trying read file , count how many times each string appears in file. using hashset on object item have created follows :

now in main trying read file , add each string in file set. while adding trying increment count of item in set appearing more once. here's implementation :

package pack;  public class item {      public string name;     public int count=1;     public item(string name)     {         this.name = name;     }     @override     public int hashcode() {         final int prime = 31;         int result = 1;         result = prime * result + count;         result = prime * result + ((name == null) ? 0 : name.hashcode());         return result;     }     @override     public boolean equals(object obj) {         if (this == obj)             return true;         if (obj == null)             return false;         if (getclass() != obj.getclass())             return false;         item other = (item) obj;         if (count != other.count)             return false;         if (name == null) {             if (other.name != null)                 return false;         } else if (!name.equals(other.name))             return false;         return true;     }  } 

for input file :

chair table teapot
teapot book table
chair floor ceiling
wall chair floor

it giving output follows :

wall appears 1 times
book appears 1 times
table appears 2 times
floor appears 2 times
teapot appears 2 times
chair appears 1 times
ceiling appears 1 times
chair appears 2 times

here set having duplicate elements don't want. correct way update objects inside set?

your item class uses count field in definition of equals , hashcode. means when call set.contains(i) second occurrence of string, contains return true since count==1. increment count, , when call set.contains(i) third occurrence of string contains return false, since count of item in set not match count of item passing contains.

to fix this, should change definition of equals , hashcode consider string , not count.

this implementation work, overly complex. create map<string, integer> , increase integer (count) each time see new occurrence of string.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -