MyObject.java Source code

Java tutorial

Introduction

Here is the source code for MyObject.java

Source

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

class MyObject {

    final int value;

    public MyObject(int val) {
        this.value = val;
    }

    @Override
    public int hashCode() {
        throw new IllegalStateException("This method must not be called");
    }
}

public class Main {
    public static void main(String[] args) {
        Set<MyObject> set = new TreeSet<>(new Comparator<MyObject>() {
            @Override
            public int compare(MyObject left, MyObject right) {
                return left.value - right.value;
            }
        });
        set.add(new MyObject(1));
        set.add(new MyObject(2));
        set.add(new MyObject(3));
        set.add(new MyObject(1)); // '1' is already in set
        System.out.println("size:" + set.size());// print 3
        System.out.println(set.remove(new MyObject(3)));
        System.out.println("size:" + set.size());
    }
}