Reputation: 61
I have written a program to insert data in a HashSet...here is the code
public class Person implements Comparable<Person>
{
private int person_id;
private String person_name;
public Person(int person_id,String person_name)
{
this.person_id=person_id;
this.person_name=person_name;
}
/* getter and setter method */
public boolean equals(Object obj)
{
Person p=(Person)obj;
if(!(p instanceof Person))
{
return false;
}
else if(this.person_id==p.person_id)
return true;
else
return false;
}
@Override
public int hashCode()
{
return person_id*6;
}
@Override
public int compareTo(Person o)
{
if(this.person_id>o.person_id)
return 1 ;
else if(this.person_id<o.person_id)
return -1;
else return 0;
}
}
I havent pasted other two classes.All i am doing in those classes is populating the data and other is main class.
Now i understand that through Java Doc Api i came to know that there is method called sort() in Collections class.Now the issue which i am is that sort mathod takes list.
here is signature from doc sort(List list). I am facing problem to sort my hashset .Somebody told me to convert HashSet into TreeSet(Thats also mentioned in one of the thread is stackoverflow)...Is this the only way
Upvotes: 2
Views: 9875
Reputation: 1981
Use LinkedHashSet
instead, as It insert elements in a sorted manner, so the set is always sorted.
See http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html more information:
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
Upvotes: 0
Reputation: 4598
Pretty much the only way. HashSet
was never meant to be sorted. It does not keep any ordering of your items, in exchange for performance of contains
, add
and remove
operations.
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
So, just use TreeSet
which keeps the sorting according to your class' natural ordering. I see your class implements Comparable
which makes it readily be used in a TreeSet
Upvotes: 9