Java core technology volume 1 Note 6. 1 interface lambda expressions internal class,. 1 lambda
6.1 an interface is a description of a group of requirements of a class. These classes must comply with the uniform format of the interface description. For example, in the Arrays class, the sort method (which can sort object Arrays) is provided that the class to which the object belongs must implement the Comparable interface.
public interface Comparable{ int compareTo(Object other)}Comparable
public interface Comparable<T>{ int compareTo(T other)}Comparable generic
The method of the interface automatically belongs to the public; the interface can define multiple methods; can define constants; the interface cannot contain instance domains;
Implementation interface: 1) Declare the class to implement the given interface (implements); 2) define all methods in the interface.
ComparaTo method implementation
1 public int ComparaTo(Object otherObject)2 {3 Employee other (Employee) otherObject;4 return Double.compare(salary, other.salary);5 }
Static Double. compare method (first parameter <second parameter, return a negative number, both are equal, return 0,
ComparaTo method generic implementation
1 class Employee implements Comparable<Employee>{2 public int ComparaTo(Employee other)3 {4 return Double.compare(salary, other.salary);5 }
}
Note that the Object parameter performs type conversion.
Why doesn't the Employee class provide a comparableTo method directly? The main reason is that java is a strong type (stronugly typed) language. When calling a method, the compiler checks whether the method exists.
1 package cc.openhome; 2 import java.util.Arrays; 3 public class JieKou { 4 public static void main(String[] args) { 5 // TODO code application logic here 6 Employee[] staff =new Employee[3]; 7 staff[0] =new Employee("harry Hacker", 75000); 8 staff[1]=new Employee("Carl Cracker", 355000); 9 staff[2]=new Employee("Tony Tester", 228000);10 Arrays.sort(staff);11 for(Employee e:staff)12 System.out.println("name="+e.getName()+",salarry="+e.getSalary());13 } 14 }15 class Employee implements Comparable<Employee>16 {17 private String name;18 private double salary;19 public Employee(String name,double salary)20 {21 this.name =name;22 this.salary=salary;23 }24 public String getName()25 {26 return name ;27 }28 public double getSalary()29 {30 return salary;31 }32 public void raiseSalary(double byPercent)33 {34 double raise =salary*byPercent/100;35 salary +=raise;36 }37 public int compareTo(Employee other)38 {39 return Double.compare(salary,other.salary);40 } 41 }
Name = harry Hacker, salarry = 75000.0 name = Tony Tester, salarry = 228000.0 name = Carl Cracker, salarry = 355000.0 successful build (total time: 0 seconds)
Run: