我必须使用compareTo() 按各种项目对动物、人类和水果的.txt 列表进行排序。现在,我正在尝试研究 Animal 类。
我需要使用compareTo()方法,该方法应该按物种内的重量排序(最大的在前),如果不是动物,则按名称排序,但命名,否则按toString()排序;
.txt 相当长,但以下是其中的示例:
human,0.5703735352,jaylen,andrews ,dallas ,,,,,
fruit,0.8782348633,salubura,green,5,,,,,
human,0.3351135254,kaylin,mspherson ,philadelphia ,,,,,
human,0.2774658203,ssott,summings ,houston ,,,,,
human,0.6909179688,phatima,hebert ,new york ,,,,,
human,0.4934692383,vivienne,stuart ,philadelphia ,,,,,
animal,0.6046142578,hamster,Monkey Butt ,46,,,,,
animal,0.4241943359,dog,Sam,60,,,,,
这是我迄今为止的动物类:
package domain;
public class Animal implements Named, Comparable<Animal> {
String species;
String name;
int weight;
/**
* Convenience constructor
*/
public Animal(String species, String name, int weight) {
this.species = species;
this.name = name;
this.weight = weight;
}
/**
* Provide text representation
*/
public String toString() {
return name + " (" + species + " / " + weight + ")";
}
/**
* Return our name
*/
public String getName() {
return name;
}
@Override
public int compareTo(Animal t) {
if (t.name.equals(name)) {
return species.compareTo(species);
}
return 0;
}
}
最佳答案
这是 compareTo
方法的一些伪代码:
@Override
public int compareTo(Animal t) {
if(this.weight != t.weight) {
return this.weight - t.weight;
} else if(!this.name.equals(t.name)){ // your custom comparision expression
return who_is_bigger;
}
return 0; // returns 0 (it seams they are equal) if all conditions are equal
}
关于java - 按 int(权重)、字符串(名称)或 toString() 对 .txt 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21611876/