我相信我的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
答案 0 :(得分: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;
}
}