Java Collections.max函数正在返回哈希代码(我想)
我相信我的Collections.max函数正在返回散列码,但老实说,我不完全确定到底发生了什么 我正在创建一个具有随机适用性值的树列表,实现一个比较器,然后试图找到下面的最高适用性值代码Java Collections.max函数正在返回哈希代码(我想),java,repast-simphony,Java,Repast Simphony,我相信我的Collections.max函数正在返回散列码,但老实说,我不完全确定到底发生了什么 我正在创建一个具有随机适用性值的树列表,实现一个比较器,然后试图找到下面的最高适用性值代码 public class Tree { public double suitability = Math.random(); public int id; public static int count = 1; public Tree(double suitability,
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();
}
}
}
我的输出如下所示:
从洞穴里学习。Tree@60f32dde
1号树的适用性为0.6114866528786418
从洞穴里学习。Tree@60f32dde
2号树的适用性为0.28381422309266247
从洞穴里学习。Tree@3312b1dd
3号树的适用性为0.8441348268153896
从洞穴里学习。Tree@3312b1dd
4号树的适用性为0.6269071898386682
从洞穴里学习。Tree@3312b1dd
5号树的适用性为0.08717540188464434
从洞穴里学习。Tree@3312b1dd
6号树的适用性为0.3810530158434646
从洞穴里学习。Tree@3312b1dd
7号树的适用性为0.0938353693923476
从洞穴里学习。Tree@3312b1dd
树编号8的适用性为0.3656868216321937
从洞穴里学习。Tree@105b3e5d
9号树的适用性为0.9717207037612301
从洞穴里学习。Tree@105b3e5d
树编号10的适用性为0.44423960773823645System.out.printlnmaxTree;调用maxTree上的toString。因为您没有重写它,所以它调用对象上的方法,该方法只输出完整的类名和一些附加信息
您需要实现toStringyourself以获得更可读的输出
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;
}
}
你的问题是什么?为什么要获得此输出,或者如何获得对象的可读字符串表示形式?看到了,您正在打印一棵树,但尚未在树上实现toString。您看到的是对象提供给您的默认toString实现。您需要覆盖树中的公共字符串toString。我的问题是为什么它不打印列表中所有值的最大值?它是。最大值是Tree的一个对象,当您尝试打印一棵树时,您会得到所看到的结果。