热门标签 | 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对类实现。


推荐阅读
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 深入解析Spring Cloud Ribbon负载均衡机制
    本文详细介绍了Spring Cloud中的Ribbon组件如何实现服务调用的负载均衡。通过分析其工作原理、源码结构及配置方式,帮助读者理解Ribbon在分布式系统中的重要作用。 ... [详细]
  • 本文详细介绍了如何构建一个高效的UI管理系统,集中处理UI页面的打开、关闭、层级管理和页面跳转等问题。通过UIManager统一管理外部切换逻辑,实现功能逻辑分散化和代码复用,支持多人协作开发。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 数据库内核开发入门 | 搭建研发环境的初步指南
    本课程将带你从零开始,逐步掌握数据库内核开发的基础知识和实践技能,重点介绍如何搭建OceanBase的开发环境。 ... [详细]
  • 本文详细记录了在基于Debian的Deepin 20操作系统上安装MySQL 5.7的具体步骤,包括软件包的选择、依赖项的处理及远程访问权限的配置。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 本文深入探讨了 Java 中的 Serializable 接口,解释了其实现机制、用途及注意事项,帮助开发者更好地理解和使用序列化功能。 ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • XNA 3.0 游戏编程:从 XML 文件加载数据
    本文介绍如何在 XNA 3.0 游戏项目中从 XML 文件加载数据。我们将探讨如何将 XML 数据序列化为二进制文件,并通过内容管道加载到游戏中。此外,还会涉及自定义类型读取器和写入器的实现。 ... [详细]
  • 从 .NET 转 Java 的自学之路:IO 流基础篇
    本文详细介绍了 Java 中的 IO 流,包括字节流和字符流的基本概念及其操作方式。探讨了如何处理不同类型的文件数据,并结合编码机制确保字符数据的正确读写。同时,文中还涵盖了装饰设计模式的应用,以及多种常见的 IO 操作实例。 ... [详细]
  • Scala 实现 UTF-8 编码属性文件读取与克隆
    本文介绍如何使用 Scala 以 UTF-8 编码方式读取属性文件,并实现属性文件的克隆功能。通过这种方式,可以确保配置文件在多线程环境下的一致性和高效性。 ... [详细]
  • MySQL索引详解与优化
    本文深入探讨了MySQL中的索引机制,包括索引的基本概念、优势与劣势、分类及其实现原理,并详细介绍了索引的使用场景和优化技巧。通过具体示例,帮助读者更好地理解和应用索引以提升数据库性能。 ... [详细]
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社区 版权所有