Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        MyKey e1 = new MyKey(1);
        MyKey e2 = new MyKey(2);

        HashMap<MyKey, Integer> map = new HashMap<>();
        map.put(e1, 1);
        map.put(e2, 2);

        System.out.println(map.get(e1));
        System.out.println(map);

        e1.setValue(9);
        System.out.println(map.get(e1));
        System.out.println(map);

        e1.setValue(2);
        System.out.println(map.get(e1));
        System.out.println(map);

        MyKey e3 = new MyKey(2);
        System.out.println(map.get(e3));
    }
}

class MyKey {
    private int n;

    public MyKey(int n) {
        this.n = n;
    }

    public void setValue(int n) {
        this.n = n;
    }

    @Override
    public int hashCode() {
        return n;
    }

    @Override
    public boolean equals(Object e) {
        if (this == e)
            return true;
        if (!(e instanceof MyKey))
            return false;
        MyKey an = (MyKey) e;
        return n == an.n;
    }

    @Override
    public String toString() {
        return "MyKey [n=" + n + "]";
    }

}