Home  >  Article  >  Java  >  Implementation example of Comparable interface and custom sorting in Java

Implementation example of Comparable interface and custom sorting in Java

黄舟
黄舟Original
2017-09-26 10:19:221093browse

The following editor will bring you an example of implementing the Comparable interface in Java to implement custom sorting. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

The example is as follows:


class Student implements Comparable{
  String name;
  int gpa;
  @Override
  public int compareTo(Object arg0) {
    // TODO Auto-generated method stub
    Student s = (Student)arg0;
    
    if(gpa == s.gpa) return name.compareTo(s.name);
    else if(gpa < s.gpa) return -1;
    else if(gpa > s.gpa) return 1;
    else return 0;
    
  }
  
  
}

class Test {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    
    int n = in.nextInt();
    
    Student[] s = new Student[n];
    
    for(int i = 0;i < n;i ++){
      s[i] = new Student();
      s[i].name = in.next();
      s[i].gpa = in.nextInt();
    }
    
    Arrays.sort(s);
    
    for (Student ss : s) 
    { 
      System.out.println(ss.name); 
      System.out.println(ss.gpa); 
    } 
  }
}

The above is the detailed content of Implementation example of Comparable interface and custom sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn