0

我相信我的 Collections.max 函数正在返回哈希码,但老实说,我并不完全确定发生了什么。

我正在创建一个具有随机适用性值的树列表,实现一个比较器,然后尝试找到最高的适用性值(代码如下)。

public class Tree {
    public double suitability = Math.random();
    public int id;
    public static int count = 1;

    public Tree(double suitability, int id) {
        this.id = count;
        count++;    
    }

    public double getSuit() {
        return suitability;
    }

    public void setSuit(double suitability) {
        this.suitability = suitability;
    }

    public void measureSuit() {
           System.out.println("Tree number " + id + " has a suitability of " + suitability);
    }

}

class SuitComp implements Comparator<Tree> {

    @Override
    public int compare(Tree o1, Tree o2) {
        return Double.compare(o1.getSuit(), o2.getSuit());
    }   
} 


public class EmeraldRunner {

    public static void main(String[] args) {

        ArrayList<Tree> trees = new ArrayList<Tree>();

        Tree tree;

        int treeCount = 10;
        for (int i = 0; i < treeCount; i++) {
        tree = new Tree(i, i);

        trees.add(tree)

        Tree maxTree = Collections.max(trees, new SuitComp());

        System.out.println(maxTree);
        tree.measureSuit();

        }

    }

}

我的输出如下所示:

learnFromCave.Tree@60f32dde

树号 1 的适用性为 0.6114866528786418

learnFromCave.Tree@60f32dde

树号 2 的适用性为 0.28381422309266247

learnFromCave.Tree@3312b1dd

树号 3 的适用性为 0.8441348268153896

learnFromCave.Tree@3312b1dd

4 号树的适用性为 0.6269071898386682

learnFromCave.Tree@3312b1dd

5 号树的适用性为 0.08717540188464434

learnFromCave.Tree@3312b1dd

6 号树的适用性为 0.3810530158434646

learnFromCave.Tree@3312b1dd

7 号树的适用性为 0.0938353693923476

learnFromCave.Tree@3312b1dd

8 号树的适用性为 0.3656868216321937

learnFromCave.Tree@105b3e5d

9 号树的适用性为 0.9717207037612301

learnFromCave.Tree@105b3e5d

10 号树的适用性为 0.44423960773823645

4

1 回答 1

0

System.out.println(maxTree);呼吁。toString()_ maxTree由于您没有覆盖它,因此它调用 Object 上的方法,该方法仅输出完整的类名和一些附加信息。

您需要toString()自己实现以获得更具可读性的输出。

public class Tree {
    public double suitability = Math.random();
    public int id;
    public static int count = 1;

    public Tree(double suitability, int id) {
        this.id = count;
        count++;
    }

    public double getSuit() {
        return suitability;
    }

    public void setSuit(double suitability) {
        this.suitability = suitability;
    }

    public void measureSuit() {
        System.out.println("Tree number " + id + " has a suitability of " + suitability);
    }

    @Override
    public String toString() {
        return "I am the tree with id " + id;
    }
}
于 2014-12-30T23:06:28.883 回答