热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java曾经有过配对类吗?——探讨Java中Pair类的历史与现状

本文探讨了Java中Pair类的历史与现状。虽然Java标准库中没有内置的Pair类,但社区和第三方库提供了多种实现方式,如ApacheCommons的Pair类和JavaFX的javafx.util.Pair类。这些实现为需要处理成对数据的开发者提供了便利。此外,文章还讨论了为何标准库未包含Pair类的原因,以及在现代Java开发中使用Pair类的最佳实践。

This question already has an answer here:

这个问题已经有了答案:

  • A Java collection of value pairs? (tuples?) 16 answers
  • 值对的Java集合?(元组)16个答案

Am I remembering incorrectly, or did Java, once upon a time, provide a Pair class as part of its API?

我是否记错了,或者Java,曾经,提供了一对类作为它的API的一部分?

10 个解决方案

#1


69  

There is no Pair in the standard framework, but the Apache Commons Lang, which comes quite close to “standard”, has a Pair.

在标准框架中没有对,但是Apache Commons Lang,它非常接近“标准”,有一对。

#2


50  

Java 1.6 and upper have two implementation of Pair (Map.Entry interface): AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry

Java 1.6和upper有两个实现的对(Map)。输入接口):AbstractMap。SimpleEntry和AbstractMap.SimpleImmutableEntry

I use it when need to store pairs (like size and object collection).

当需要存储对(比如大小和对象集合)时,我使用它。

This piece from my production code:

这是我的产品代码:

public Map>>>>>
        getEventTable(RiskClassifier classifier) {
    Map>>>>> l1s = new HashMap<>();
    Map>>> l2s = new HashMap<>();
    Map> l3s = new HashMap<>();
    List events = new ArrayList<>();
    ...
    map.put(l3s, events);
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}

Code looks complicated but instead of Map.Entry you limited to array of object (with size 2) and lose type checks...

代码看起来很复杂,而不是映射。输入您限制为对象数组(大小为2)和丢失类型检查…

#3


31  

A Pair class :

两类:

public class Pair {

    private final K element0;
    private final V element1;

    public static  Pair createPair(K element0, V element1) {
        return new Pair(element0, element1);
    }

    public Pair(K element0, V element1) {
        this.element0 = element0;
        this.element1 = element1;
    }

    public K getElement0() {
        return element0;
    }

    public V getElement1() {
        return element1;
    }

}

usage :

用法:

Pair pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();

Immutable, only a pair !

不可变,只有一对!

#4


14  

This should help.

这应该帮助。

To sum it up: a generic Pair class doesn't have any special semantics and you could as well need a Tripplet class etc. The developers of Java thus didn't include a generic Pair but suggest to write special classes (which isn't that hard) like Point(x,y), Range(start, end) or Map.Entry(key, value).

概括起来:一个普通的Pair类没有任何特殊的语义,您也可以需要一个Tripplet类等等。Java的开发人员没有包含一个通用的Pair,而是建议编写特殊的类(这并不是很困难),比如Point(x,y), Range(开始,结束)或者Map。条目(关键字,值)。

#5


13  

There are lots of implementation around here, but all the time something is missing , the Override of equal and hash method.

这里有很多实现,但是所有的时间都缺失了,比如重写了equal和hash方法。

here is a more complete version of this class:

下面是这个类的更完整版本:

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.secOnd= second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair p = (Pair) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (secOnd== null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static  Pair  create(A a, B b) {
        return new Pair(a, b);
    }
}

#6


11  

No, but it's been requested many times.

没有,但是已经被要求过很多次了。

#7


5  

Many 3rd party libraries have their versions of Pair, but Java has never had such a class. The closest is the inner interface java.util.Map.Entry, which exposes an immutable key property and a possibly mutable value property.

许多第三方库都有它们的版本,但是Java从来没有这样的类。最接近的是内部接口java.util.Map。条目,它公开了一个不可变的键属性和一个可能的可变值属性。

#8


3  

If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set

如果您想要一对(而不是所谓的键值对),只需要将两个通用数据放在一起,这两种解决方案都不能真正方便地使用,因为第一个(或所谓的密钥)是不能更改的(在Apache Commons Lang的pair中,也不是在AbstractMap.SimpleEntry中)。他们有自己的理由,但是你可能需要改变这两个组件。这是一个对两个元素都可以设置的类。

public class Pair {
    private First first;
    private Second second;

    public Pair(First first, Second second) {
        this.first = first;
        this.secOnd= second;
    }

    public void setFirst(First first) {
        this.first = first;
    }

    public void setSecond(Second second) {
        this.secOnd= second;
    }

    public First getFirst() {
        return first;
    }

    public Second getSecond() {
        return second;
    }

    public void set(First first, Second second) {
        setFirst(first);
        setSecond(second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair pair = (Pair) o;

        if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
        if (second != null ? !second.equals(pair.second) : pair.second != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }
}

#9


1  

It does seem odd. I found this thread, also thinking I'd seen one in the past, but couldn't find it in Javadoc.

这似乎很奇怪。我发现了这个线程,也认为我曾经看到过一个线程,但是在Javadoc中找不到它。

I can see the Java developers' point about using specialised classes, and that the presence of a generic Pair class could cause developers to be lazy (perish the thought!)

我可以看到Java开发人员使用专门化类的观点,并且一个泛型对类的存在可能会导致开发人员懒惰(破坏思想!)

However, in my experience, there are undoubtedly times when the thing you're modelling really is just a pair of things and coming up with a meaningful name for the relationship between the two halves of the pair, is actually more painful than just getting on with it. So instead, we're left to create a 'bespoke' class of practically boiler-plate code - probably called 'Pair'.

然而,在我的经验中,毫无疑问的是,当你做模特的时候,你所做的只是一件事,并且为这两个人之间的关系想出一个有意义的名字,实际上比仅仅做一件事要痛苦得多。因此,我们只能创建一个“定制”类的实际样板代码——可能叫做“Pair”。

This could be a slippery slope, but a Pair and a Triplet class would cover a very large proportion of the use-cases.

这可能是一个滑坡,但一对和一个三胞胎班将涵盖很大比例的用例。

#10


0  

No but JavaFX has it.

不,但是JavaFX有。

Cf. Stack Overflow: Java Pair class implementation

堆栈溢出:Java对类实现。


推荐阅读
author-avatar
赵娜supergirl
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有