1

I'm trying to find a collection which won't store multiple instances of the same object, but will store identical objects with distinct references.

For example, the code:

import java.awt.Rectangle;
import java.util.HashSet;

public class setTest {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle();
        HashSet<Rectangle> set = new HashSet<>();

        System.out.println("Add r1      : " + set.add(r1));
        System.out.println("Contains r2 : " + set.contains(r2));
        System.out.println("Add r2      : " + set.add(r2));
        System.out.println();

        r2.grow(100,100);
        System.out.println("Grow r2");
        System.out.println("Contains r2 : " + set.contains(r2));
        System.out.println("Add r2      : " + set.add(r2));
        System.out.println("Contains r2 : " + set.contains(r2));
        System.out.println();

        r2.grow(100,100);
        System.out.println("Grow r2");
        System.out.println("Contains r2 : " + set.contains(r2));
    }
}

produces the result:

Add r1      : true
Contains r2 : true
Add r2      : false

Grow r2
Contains r2 : false
Add r2      : true
Contains r2 : true

Grow r2
Contains r2 : false

Whereas I would like an implementation which produces:

Add r1      : true
Contains r2 : false
Add r2      : true

Grow r2
Contains r2 : true
Add r2      : false
Contains r2 : true

Grow r2
Contains r2 : true

Does something like that exist? Or would I need to create a collection like that myself?

bitwiseWho
  • 11
  • 1
  • 2
    There’s IdentityHashMap and you can create Sets from Map instances. So yes: `Collections.newSetFromMap(new IdentityHashMap<>());` – Felix Oct 08 '21 at 18:56
  • Thank you, all! IdentityHashMap is exactly what I was looking for. – bitwiseWho Oct 08 '21 at 20:17

0 Answers0