Skip to content

Latest commit

 

History

History
82 lines (62 loc) · 1.9 KB

File metadata and controls

82 lines (62 loc) · 1.9 KB

19. Pool Demo

String Constant Pool concept can be understood from the below sample implementation

Copy the below code in you code editor and run Pool.java .

package poolDemo;

import java.util.HashMap;
import java.util.Objects;

public final class MyPair{
    // not a thread safe implementation
    private static final HashMap<MyPair,MyPair> POOL_RESOURCE = new HashMap<>();

    private final int x;
    private final int y;

    MyPair(int a, int b){
        this.x = a;
        this.y = b;
    }

    public int getX(){
        return this.x;
    }

    public int getY(){
        return this.y;
    }

    public MyPair usePool(){
        MyPair.POOL_RESOURCE.putIfAbsent(this,this);
        return MyPair.POOL_RESOURCE.get(this);
    }

    @Override
    public boolean equals(Object o){
        if(this.getClass() != o.getClass()) return false;
        MyPair myPair = (MyPair) o;
        return this.x == myPair.x && this.y == myPair.y;
    }

    @Override
    public int hashCode(){
        return Objects.hash(this.x,this.y);
    }

    @Override
    public String toString(){
        return "MyPair (" + this.x + ", " + this.y + ")";
    }
}
package poolDemo;

public class Pool {

    public static void main(String[] args){
        MyPair myPair = new MyPair(2,3);
        MyPair myPair1 = new MyPair(2,3);

        MyPair myPair2 = myPair.usePool();
        MyPair myPair3 = new MyPair(2,3).usePool();
        MyPair myPair4 = new MyPair(2,3).usePool();
        System.out.println(myPair == myPair1); // false
        System.out.println(myPair == myPair2); // true
        System.out.println(myPair2 == myPair3); // true
        System.out.println(myPair3 == myPair4); // true

        System.out.println();
        System.out.println(myPair.equals(myPair1)); // true
        System.out.println(myPair.equals(myPair2)); // true
        System.out.println(myPair2.equals(myPair3)); //  true
    }

}