0
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);
    }
}

Here I have a Node class. I want to be able to insert the nodes in a TreeSet and sort them by their location in memory. How can I return the difference of the memory locations in the function compareTo?

StackExchange123
  • 1,871
  • 9
  • 24
  • Does this answer your question? [Memory address of variables in Java](https://stackoverflow.com/questions/1961146/memory-address-of-variables-in-java) – Przemysław Głębocki Apr 23 '20 at 12:50
  • Firstly, how do you define "*position in memory*"? Memory is not just like a big array with integer indices, it's a hierarchy ranging from ultra-fast registers to increasingly slower caches, ram, disk, etc. Secondly, the JVM acts as an abstraction layer so it's not possible. – Michael Apr 23 '20 at 12:52

2 Answers2

2

The memory location of an object is not available to a (pure) Java program.

Even if you use native code or Unsafe to get the location of an object, there is no guarantee that the GC won't move it ... without any notice. So if you were to order the objects in a collection by their memory address, the collection would not stay ordered.

On the other hand, you could use System.identityHashCode(Object) to get a 32 bit code that will not change for the lifetime of the object. Even if the GC moves the object.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Why would you want to order elements by their memory address. You can't rely on that cause it can change over time. Read here