Created
July 6, 2021 03:47
-
-
Save htsign/f9f5d4cfa2e8f9d9969757c1c45be82f to your computer and use it in GitHub Desktop.
nicely worked on Java8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Objects; | |
public class Pair<Left, Right> { | |
private static final List<Pair<?, ?>> cache = new ArrayList<>(); | |
public final Left left; | |
public final Right right; | |
private Pair(Left left, Right right) { | |
this.left = left; | |
this.right = right; | |
} | |
public static synchronized <Left, Right> Pair<Left, Right> of(Left left, Right right) { | |
Pair<Left, Right> pair = new Pair<>( | |
Objects.requireNonNull(left), | |
Objects.requireNonNull(right)); | |
return pair.reallocate(); | |
} | |
@SuppressWarnings("unchecked") | |
private Pair<Left, Right> reallocate() { | |
return (Pair<Left, Right>) cache.stream() | |
.filter(this::equals) | |
.findFirst() | |
.orElseGet(() -> { | |
cache.add(this); | |
return this; | |
}); | |
} | |
@Override | |
public int hashCode() { | |
return left.hashCode() ^ right.hashCode(); | |
} | |
@Override | |
public boolean equals(Object other) { | |
if (other instanceof Pair) { | |
Pair<?, ?> p = (Pair<?, ?>) other; | |
return left.equals(p.left) && right.equals(p.right); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment