fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. (new Ideone()).solve();
  13.  
  14. }
  15.  
  16. private void solve() {
  17. int arr[] = new int[]{2,2,2};
  18. int n = arr.length;
  19. Pair pairs[] = new Pair[n];
  20. for(int i = 0; i < n; i++) {
  21. pairs[i] = new Pair(i, arr[i]);
  22. }
  23. TreeSet<Pair> set = new TreeSet<>((p1, p2) -> {
  24. if(p1.val == p2.val) return p1.idx-p2.idx;
  25. return p1.val-p2.val;
  26. });
  27. // HashSet<Pair> set = new HashSet<>();
  28. for(int i = 0; i < arr.length; i++)
  29. set.add(pairs[i]);
  30. System.out.println(set);
  31. }
  32.  
  33. class Pair {
  34. int idx, val;
  35. Pair(int idx, int val) {
  36. this.idx = idx;
  37. this.val = val;
  38. }
  39.  
  40. public int hashCode() {
  41. return idx;
  42. }
  43.  
  44. public boolean equals(Object ob) {
  45. return(this.idx == ((Pair)ob).idx);
  46. }
  47.  
  48. public String toString() {
  49. return("{ "+idx+", "+val+" }");
  50. }
  51. }
  52. }
Success #stdin #stdout 0.14s 56092KB
stdin
Standard input is empty
stdout
[{ 0, 2 }, { 1, 2 }, { 2, 2 }]