Java implements the Comparable interface to achieve custom sorting, javacomparable

Source: Internet
Author: User

Java implements the Comparable interface to achieve custom sorting, javacomparable

 1 class Student implements Comparable{ 2     String name; 3     int gpa; 4     @Override 5     public int compareTo(Object arg0) { 6         // TODO Auto-generated method stub 7         Student s = (Student)arg0; 8          9         if(gpa == s.gpa) return name.compareTo(s.name);10         else if(gpa < s.gpa) return -1;11         else if(gpa > s.gpa) return 1;12         else return 0;13         14     }15     16     17 }18 19 class Test {20     public static void main(String[] args){21         Scanner in = new Scanner(System.in);22         23         int n = in.nextInt();24         25         Student[] s = new Student[n];26         27         for(int i = 0;i < n;i ++){28             s[i] = new Student();29             s[i].name = in.next();30             s[i].gpa = in.nextInt();31         }32         33         Arrays.sort(s);34         35         for (Student ss : s)  36         {  37             System.out.println(ss.name);  38             System.out.println(ss.gpa);  39         }  40     }41 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.