[英]Trying to implement the interface Comparable
只是想知道這個錯誤是什么意思,以及我該如何解決。
錯誤:學生類型必須實現繼承的抽象方法java.lang.Comparable.compareTo(java.lang.Object)
我試圖實現這一點,所以我可以使用該類的compareTo方法。
非常感謝你的幫助!
import java.util.*;
import java.io.*;
public class Student implements Comparable
{
private String name;
private double gpa;
public Student()
{
name = "";
gpa = 0.0;
}//end default constructor
public Student(String n, double g)
{
name = n;
gpa = g;
}//end two arg constructor
public double getGPA()
{
return gpa;
}
public String getName()
{
return name;
}
public void setGPA(double g)
{
this.gpa = g;
}
public void setName(String n)
{
this.name = n;
}
public String toString()
{
return " Name: " + name + " GPA: " + gpa;
}
public static void compareTo()
{
}
}//end class
您要做的就是實現可比較的接口,並在要排序的類中重寫compareTo()方法。 在compareTo方法內部,您必須提及對象應在哪個基礎上排序。 下面的代碼將對此有所幫助:
public class Student implements Comparable<Student>
{
private String name;
private double gpa;
public Student()
{
name = "";
gpa = 0.0;
}//end default constructor
public Student(String n, double g)
{
name = n;
gpa = g;
}//end two arg constructor
public double getGPA()
{
return gpa;
}
public String getName()
{
return name;
}
public void setGPA(double g)
{
this.gpa = g;
}
public void setName(String n)
{
this.name = n;
}
public String toString()
{
return " Name: " + name + " GPA: " + gpa;
}
public Integer compareTo(Student student)
{
// if object is getting sorted on the basis of Name
return this.getName().compareTo(student.getName())
// if object is getting sorted on the basis of gpa
return Double.valueOf(this.gpa).compareTo(Double.valueOf(student.getGPA()));
}
}//end class
由於您使用的是原始數據類型double而不是Object Double,因此我們需要使用Double.valueOf(this.gpa)獲取對象。根據需要,您僅應使用一個return語句。
為了正確實現Comparable
接口,您必須對代碼進行以下更改。
(1)指定您的類可與之媲美的對象類型:
public class Student implements Comparable<Student>
(2) compareTo
方法的對應簽名如下:
public int compareTo(Student other)
當然,您也必須實現compareTo
方法的主體。
this
實例比other
參數“小”,則compareTo
應該返回一個負數 。 this
實例比other
參數“更大”,則compareTo
應該返回一個正數。 this
實例與參數other
視為“具有相同的值”,則compareTo
應該返回0
。 您可以參考官方Java文檔以獲取有關實現細節的更多信息。
請注意, Interface Comparable<T>
是通用接口。 這里T
是類型(主要是類,接口)。 您想將Student
與其他類型( Student
)進行比較。
因此,您必須將type( T
) Student
傳遞給Comparable<T>
。
因此,您將其更改為
public class Student implements Comparable<Student>
還有一點,您必須將Comparable<T>
接口實現為相同的方法簽名,並將類型返回給Student
類。
public int compareTo(Student anotherStudent)
你寫
public static void compareTo()
不遵循接口Comparable<T>
方法簽名和 Student
類中的返回類型 。
在這里,您應該實現特定於域的邏輯。 我不知道您想如何執行它? 您可以按字母順序比較名稱,也可以根據其CGPA進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.