7-2 jmu-Java-04 advanced object-oriented interfaces -Comparable -01-

Copyright: Yeah yeah yeah, knock yourself small code to be cute, do not copy oh. https://blog.csdn.net/qq_43201999/article/details/90047399

7-2 jmu-Java-04 advanced object-oriented interfaces -Comparable -01-

Problem Description:
Arrays.sort custom object can not be sorted. Now we hope PersonSortable object class custom, using Arrays.sort sort.

1. Preparation PersonSortable class

Properties: private name (String), private age (int)
with a reference constructor: parameter name, age
toString function: Returns the format: name-age
implement Comparable interface: implement the first sort name in ascending order, if the name the same as the pair of age ascending order

2.main method

N first inputs
the input n-th row name age, and creates an array of n objects into
the sort the array output.
The last line uses System.out.println (Arrays.toString (PersonSortable.class.getInterfaces ()) ); PersonSortable all output interfaces implemented.

Code:

import java.util.*;
class PersonSortable implements Comparable<PersonSortable> {
    private String name;
    private int age;
    public PersonSortable(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return name + "-" + this.age;
    }
    public int compareTo(PersonSortable stu){
		if(this.name.compareTo(stu.name)>0)return 1;
		else if(this.name.compareTo(stu.name)<0)return -1;
		else{
			if(this.age<stu.age)return -1;
			else return 1;
		}
    }
}
public class Main{
    public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		PersonSortable stu[]=new PersonSortable[n];
		for(int i=0;i<n;i++) {
			String name=sc.next();
			int age=sc.nextInt();
			stu[i]=new PersonSortable(name,age);
		}
		sc.close();
        java.util.Arrays.sort(stu);
        for(int i=0;i<stu.length;i++){
            System.out.println(stu[i]);
        }
		System.out.println(Arrays.toString(PersonSortable.class.getInterfaces()));
    }
}

Well, almost running about to be all right, if there is optimization program, you can leave Oh, I wish you good luck.

Guess you like

Origin blog.csdn.net/qq_43201999/article/details/90047399