【发布时间】:2020-08-06 18:58:21
【问题描述】:
package com.company;
import java.util.TreeSet;
public class Main {
public static class Node implements Comparable<Node>
{
public int value;
public Node(int value) {
this.value = value;
}
@Override
public int compareTo(Node node) {
// Memory location of this - memory location of node.
return 0;
}
}
public static void main(String[] args) {
TreeSet<Node> set = new TreeSet<>();
Node n = new Node(5);
set.add(n);
for (var node : set)
System.out.println(node.value);
}
}
这里我有一个Node 类。我希望能够将节点插入TreeSet 并按它们在内存中的位置对它们进行排序。如何返回函数compareTo中内存位置的差异?
【问题讨论】:
-
这能回答你的问题吗? Memory address of variables in Java
-
首先,如何定义“在内存中的位置”?内存不仅仅是一个具有整数索引的大数组,它是一个层次结构,从超快的寄存器到越来越慢的缓存、内存、磁盘等。其次,JVM 充当抽象层,所以这是不可能的。
标签: java sorting memory-address comparable