2015-05-17 15 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

相关问题