java - 按 int(权重)、字符串(名称)或 toString() 对 .txt 列表进行排序

标签 java sorting compareto

我必须使用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/

相关文章:

java - 在 EditText 中添加一个字符

java - Collections.sort(list) 不适用于(链接的)哈希集背后的原因?

java - 忽略标点符号的排序 (Java)

java - Apache POI 在应用 PropertyTemplate 边框时用黑色而不是所需的自定义颜色填充 XSSF 单元格

java - 从套接字流读取时是否需要线程 sleep ?

Java冒泡排序算法计时器问题

javascript - 按下一篇文章对文章列表进行排序

java - 用于排序整数的 compareTo 方法

java - 在Java中如何对带有整数的字符串进行排序?

java - selenium 3.0 webdriver for safari 10 on yosemite