2015-05-17 49 views
-4

所以我給了預先寫好的代碼,我必須填寫comepareTo函數。它需要比較字符串並按長度排序,但我不確定該方法中傳遞的是什麼。不理解什麼被傳入方法

import java.util.Arrays; 

public class testString implements Comparable<testString> { 
    String tempStr; 

public testString(String str) { 
    tempStr = str; 
} 

public String toString() { 
    return tempStr; 
} 

public int compareTo(testString Str2) { 

    return 0; 
} 


String [] list = {"dog", "cat", "lion", "python", "giraffe", "emu"}; 
testString [] list2 = new testString[list.length]; 
for (int i=0; i<list2.length; i++) { 
    list2[i] = new testString(list[i]); 
} 

我不太確定是什麼類型正在傳遞到compareTo功能(STR2)。
我認爲這將是一個列表,我可以用for循環運行它,但如果我嘗試Str2 [1],那會給我錯誤。

回答

0

Str2參數是類型爲testString(您定義的類)的對象。 該方法用於比較當前對象和作爲參數接收的對象。爲了使這種比較有意義,對象必須是相同的類型。

也檢查Comparable接口的API文檔。 https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

方法compareTo是此接口的一部分。

在你的情況下,最簡單的實現將是: 返回this.tempStr.compareTo(Str2.tempStr);

當然

,STR2不能爲空:)

0

你會怎樣創建一個對象,如果你只是想存儲在首位的字符串?

無論如何,只需要通過將參數長度減去tempStr值的長度來實現比較方法。最後你只需要返回結果。

+0

好吧,我很困惑,我得到的第一個字符串,但它存儲在臨時字符串。我最終得到它,所以它返回,1,0或-1。謝謝。 – john12345

相關問題