Advertisement
fr1sk

CustomCompare

Jun 10th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.List;
  5. import java.util.Set;
  6. import java.util.TreeSet;
  7.  
  8. class Animals implements Comparable<Animals>{
  9.     private String vrsta;
  10.     public Animals(String vrsta) {
  11.         this.vrsta = vrsta;
  12.     }
  13.     public String getVrsta() {
  14.         return vrsta;
  15.     }
  16.     public void setVrsta(String vrsta) {
  17.         this.vrsta = vrsta;
  18.     }
  19.     @Override
  20.     public String toString() {
  21.         return "vrsta";
  22.     }
  23.     @Override
  24.     public int hashCode() {
  25.         final int prime = 31;
  26.         int result = 1;
  27.         result = prime * result + ((vrsta == null) ? 0 : vrsta.hashCode());
  28.         return result;
  29.     }
  30.     @Override
  31.     public boolean equals(Object obj) {
  32.         if (this == obj)
  33.             return true;
  34.         if (obj == null)
  35.             return false;
  36.         if (getClass() != obj.getClass())
  37.             return false;
  38.         Animals other = (Animals) obj;
  39.         if (vrsta == null) {
  40.             if (other.vrsta != null)
  41.                 return false;
  42.         } else if (!vrsta.equals(other.vrsta))
  43.             return false;
  44.         return true;
  45.     }
  46.      public int compareTo(Animals person){
  47.         return person.vrsta.compareTo(vrsta);
  48.      }
  49.    
  50. }
  51.  
  52.  
  53. public class CustomCompares {
  54.     public static void main(String[] args) {
  55.         List<Animals> lista= new ArrayList<Animals>();
  56.         Set<Animals> set = new TreeSet<Animals>();
  57.        
  58.        
  59.         addItems(lista);
  60.         addItems(set);
  61.         Collections.sort(lista);
  62.         printItems(lista);
  63.         System.out.println();
  64.         printItems(set);
  65.     }
  66.  
  67.     private static void addItems(Collection<Animals> col) {
  68.         col.add(new Animals("predrag"));
  69.         col.add(new Animals("zoran"));
  70.         col.add(new Animals("goran"));
  71.         col.add(new Animals("dzon"));
  72.        
  73.     }
  74.    
  75.     private static void printItems (Collection<Animals> col) {
  76.         for(Animals elementi: col){
  77.             System.out.println(elementi.getVrsta());
  78.         }
  79.        
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement