在Java中实现Pair类的最佳方法

在Java中实现Pair类的最佳方法,java,tuples,Java,Tuples,我使用Map.Entry为Java中的Pair类编写了以下代码。有人有什么改进的建议吗?对我来说,类需要满足的最重要的标准是,构造一对对象很容易,而equals将按照我希望的方式工作(对中两个对象以相同顺序相等意味着对的相等)。代码似乎按预期运行,没有用于任何会占用系统内存的地方,但任何优化都将受到赞赏 import java.util.*; public class Pair { // Return a map entry (key-value pair) from the spec

我使用Map.Entry为Java中的Pair类编写了以下代码。有人有什么改进的建议吗?对我来说,类需要满足的最重要的标准是,构造一对对象很容易,而equals将按照我希望的方式工作(对中两个对象以相同顺序相等意味着对的相等)。代码似乎按预期运行,没有用于任何会占用系统内存的地方,但任何优化都将受到赞赏

import java.util.*;

public class Pair {
    // Return a map entry (key-value pair) from the specified values
    public static <T, U> Map.Entry<T, U> of(T first, U second) {
        return new AbstractMap.SimpleEntry<>(first, second);
    }

    private Map.Entry entry;

    public Pair (Object x, Object y) {
        Set<Map.Entry> entries = new HashSet<>();
        entries.add(Pair.of(x, y));
        Object[] setArray = entries.toArray();
        this.entry = (Map.Entry) setArray[0];
    }

    public Object getKey() {
        return entry.getKey();
    }
    public Object getValue() {
        return entry.getValue();
    }


    @Override
    public boolean equals(Object o)
    {
        if (o instanceof Pair) {
            Pair pair = (Pair) o;
            return ( (entry.getKey().equals(pair.getKey())) && (entry.getValue().equals(pair.getValue())) );
        }
        return false;
    }

    @Override
    public int hashCode() {
            return Objects.hash(entry.getKey(), entry.getValue());
    }

    @Override
    public String toString() {
            return String.format( "(" +entry.getKey().toString() + ", " + entry.getValue().toString() + ")" );
    }
}
import java.util.*;
公共类对{
//从指定值返回映射项(键值对)
公共静态映射。输入(T第一,U第二){
返回新的AbstractMap.SimpleEntry(第一,第二);
}
私人地图。入口;
公共对(对象x、对象y){
Set entries=newhashset();
添加(一对(x,y));
Object[]setArray=entries.toArray();
this.entry=(Map.entry)setArray[0];
}
公共对象getKey(){
return entry.getKey();
}
公共对象getValue(){
返回条目.getValue();
}
@凌驾
公共布尔等于(对象o)
{
如果(对的o实例){
配对=(配对)o;
返回((entry.getKey().equals(pair.getKey())&&(entry.getValue().equals(pair.getValue()));
}
返回false;
}
@凌驾
公共int hashCode(){
返回Objects.hash(entry.getKey(),entry.getValue());
}
@凌驾
公共字符串toString(){
返回String.format(“(“+entry.getKey().toString()+”,“+entry.getValue().toString()+”);
}
}
我一直在考虑使用Collections.singletonMap而不是Map.Entry

到目前为止,我已经使用以下方法成功地测试了我的代码:

import java.util.HashMap;

public class Main {

    public static void main(String[] args) {
        HashMap<Pair, Integer> testMap = new HashMap<>();
        Pair onThrup = new Pair(1, 3);
        System.out.println(onThrup); //Prints contents of Pair, not hash
        testMap.put(onThrup, 7);
        Pair unoTres = new Pair(1, 3);
        System.out.println(onThrup.equals(unoTres));
        System.out.println(testMap.containsKey(onThrup));
        System.out.println(unoTres.hashCode() == onThrup.hashCode());
        System.out.println(testMap.containsKey(unoTres)); // Should be, and is, true
    }
}
import java.util.HashMap;
公共班机{
公共静态void main(字符串[]args){
HashMap testMap=新的HashMap();
配对=新配对(1,3);
System.out.println(onThrup);//打印对的内容,而不是散列
testMap.put(onThrup,7);
对unoTres=新对(1,3);
System.out.println(onThrup.equals(unoTres));
System.out.println(testMap.containsKey(onThrup));
System.out.println(unoTres.hashCode()==onThrup.hashCode());
System.out.println(testMap.containsKey(unoTres));//应该是,并且是真的
}
}
Java 16包括:

不确定什么是最好的,如果可用(Java16),我会使用它



我确实希望能够运行一个循环,在重新使用相同的变量名(如p)的同时构造新的对,而不会出现问题。hash的相等性和.equals()下的相等性应基于该对的内容,以便在新对上运行HashMap.containsKey时,如果该对的值与先前作为键值对中的键添加到HashMap中的对的值相同,则将返回true。我相信我这里的代码确实可以做到这一点,但是如果有人对格式化或效率有什么建议,可能有更好的方法来编写这个类。我认为您可以为这对对象必须包含的每个对象使用一个字段。它将不再需要Map.Entry。您还可以使用泛型生成类签名,如
Pair
。无论如何,我真的不明白为什么要使用成对集合构造函数。它可以简化,若你们想让Pair类中的equals和hashCode方法可用作映射键,那个么你们必须重写它们。您可以查看是否需要了解它。您还可以使用第三方Pair实现—来自Apache Commons的
ImmutablePair
,或者来自VavrI的
Tuple2
,因为条目是抽象的,无法实例化。我相信hashCode和equals的重写是成功的。
public record Pair<K, V>(K key, V value) {
    // intentionally empty
}
var one = new Pair<Integer, String>(1, "one");
var two = new Pair(2, "two");
System.out.println(one);   // Pair[key=1, value=one]
if (!one.equals(two))
    System.out.printf("not same as Pair for %d%n", two.key());