posted on: 2011-02-10 10:59:26
A simple example of a Comparator and a TreeSet to show what gets inserted and how the ordering works.
>A simple example of a Comparator and a TreeSet to show what gets inserted and how the ordering works.
import java.util.TreeSet; import java.util.Comparator; public class TestCase{ public static void main(String[] args){ TreeSet<Rock> set = new TreeSet<Rock>(new Comparator<Rock>(){ public int compare(Rock a, Rock b){ return a.value - b.value; } } ); set.add(new Rock(1,"one")); set.add(new Rock(2,"two")); set.add(new Rock(2,"other two")); for(Rock r: set) System.out.println(r.name); } } class Rock{ int value; String name; Rock(int v, String s){ value = v; name = s; } }
and the output:
one two
Note the lowest value is first and the second time the '2' object is attempted to insert it does not get inserted.
Comments
beatrice
2012-12-19 08:30:29
Thanks
4b4dguy
2013-01-18 21:55:43
Nice! (Y) Thanks
JohnQ
2013-03-12 04:57:47
*Exactly* the example I was after. Thanks!
nikhitha
2013-08-04 14:35:55
what if we override equals and hashcode
jeff
2013-08-14 15:06:03
equals and hashcode wont help u
<script></script>
2014-03-03 04:53:47
<script>alert("Adam la chupa hihi");</script>
aa
2014-03-14 08:15:59
thanks! simple and neat!
some noob
2014-08-30 17:04:30
Thank you, master