简体   繁体   English

在 Java 中实现一对 class 的最佳方法

[英]Best way to implement a Pair class in Java

I have written the following code for a Pair class in Java using Map.Entry.我使用 Map.Entry 为 Java 中的一对 class 编写了以下代码。 Does anyone have any recommendations for improving it?有没有人有任何改进它的建议? The most important criteria for me that the class needed to meet were that it would be easy to construct a Pair and that.equals would work the way I wanted it to (equality of the two objects in the Pair in the same order means equality of the Pairs).对我来说 class 需要满足的最重要的标准是它很容易构造一个 Pair 并且 that.equals 会按照我想要的方式工作(Pair 中两个对象以相同的顺序相等意味着相等对)。 The code seems to function as intended and is not used in anything that is taxing my system's memory yet, but any optimizations would be appreciated.该代码似乎符合预期的 function 并且未用于对我的系统的 memory 征税的任何内容,但任何优化将不胜感激。

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() + ")" );
    }
}

I have been considering using Collections.singletonMap instead of Map.Entry.我一直在考虑使用 Collections.singletonMap 而不是 Map.Entry。

So far, I have successfully tested my code using the following:到目前为止,我已经使用以下代码成功测试了我的代码:

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
    }
}

Java 16 includes Record Classes : Java 16 包括记录类

public record Pair<K, V>(K key, V value) {
    // intentionally empty
}

Creates a class with final fields, methods to retrieve key and value , equals , hashCode and toString methods.创建一个class ,其中包含最终字段、检索keyvalue的方法、 equalshashCodetoString方法。

Usage example:使用示例:

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());

not sure what is best, if available (java 16) I would use that不确定什么是最好的,如果有的话(java 16)我会用那个

JLS 8.10 JLS 8.10
JEP 395杰普 395

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM