[Java基础] 2个Pair工具类比较

2024-05-14 07:38
文章标签 java 基础 工具 比较 pair

本文主要是介绍[Java基础] 2个Pair工具类比较,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

之前再开发过程中, 发现有2个Pair类, 2个Pair类之间还是有一些差别和联系的, 将考究内容记录于此.
PS: 后续, 我们可以探究下Tuplate 三元组和多元组.


Pair类解析

javafx.util.Pair Java原生Pair类

基本使用Demo.

package com.yanxml.util.pair.demo;import javafx.util.Pair;/*** Pair 相关使用. Demo1* @author seanYanxml* @date 2022-02-28 00:00:00*/
public class PairInstanceDemo1 {public static void main(String[] args) {// 创建Pair createPair = new Pair<String, String>("abc","bcd");// 获取左边值System.out.println("key:" + createPair.getKey());// 获取右边值System.out.println("Value:" + createPair.getValue());// Pair 创建完成后. 无法修改.}
}

预计输出:

key:abc
Value:bcd
详解

在这里插入图片描述
通过结构, 我们可以发现. 这个类就这些基本成员和方法. 其中最主要的就是 构造函数 getKeygetValue 这3个方法.

package javafx.util;import java.io.Serializable;
import javafx.beans.NamedArg;/*** <p>A convenience class to represent name-value pairs.</p>* @since JavaFX 2.0*/
public class Pair<K,V> implements Serializable{/*** Key of this <code>Pair</code>.*/private K key;/*** Gets the key for this pair.* @return key for this pair*/public K getKey() { return key; }/*** Value of this this <code>Pair</code>.*/private V value;/*** Gets the value for this pair.* @return value for this pair*/public V getValue() { return value; }/*** Creates a new pair* @param key The key for this pair* @param value The value to use for this pair*/public Pair(@NamedArg("key") K key, @NamedArg("value") V value) {this.key = key;this.value = value;}/*** <p><code>String</code> representation of this* <code>Pair</code>.</p>** <p>The default name/value delimiter '=' is always used.</p>**  @return <code>String</code> representation of this <code>Pair</code>*/@Overridepublic String toString() {return key + "=" + value;}/*** <p>Generate a hash code for this <code>Pair</code>.</p>** <p>The hash code is calculated using both the name and* the value of the <code>Pair</code>.</p>** @return hash code for this <code>Pair</code>*/@Overridepublic int hashCode() {// name's hashCode is multiplied by an arbitrary prime number (13)// in order to make sure there is a difference in the hashCode between// these two parameters://  name: a  value: aa//  name: aa value: areturn key.hashCode() * 13 + (value == null ? 0 : value.hashCode());}/*** <p>Test this <code>Pair</code> for equality with another* <code>Object</code>.</p>** <p>If the <code>Object</code> to be tested is not a* <code>Pair</code> or is <code>null</code>, then this method* returns <code>false</code>.</p>** <p>Two <code>Pair</code>s are considered equal if and only if* both the names and values are equal.</p>** @param o the <code>Object</code> to test for* equality with this <code>Pair</code>* @return <code>true</code> if the given <code>Object</code> is* equal to this <code>Pair</code> else <code>false</code>*/@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o instanceof Pair) {Pair pair = (Pair) o;if (key != null ? !key.equals(pair.key) : pair.key != null) return false;if (value != null ? !value.equals(pair.value) : pair.value != null) return false;return true;}return false;}}

通过上述代码可以发现, Pair的左右都是通过2个Object来完成的, 和我们平常使用的类定义的成员变量并无区别.

但是, 值得注意的是. Pair是无修改方法的, 也就是说. 当Pair声明后, 其中的变量就不可变了.


org.apache.commons.lang3.tuple.Pair lang3包内的Pair类

看过了Java元素的Pair包, 我们再看下lang3的Pair类是如何定义的.

  • demo方法
package com.yanxml.util.pair.demo;import org.apache.commons.lang3.tuple.Pair;/*** Pair 相关使用. Demo2* @author seanYanxml* @date 2022-02-28 00:00:00*/
public class PairInstanceDemo2 {public static void main(String[] args) {Pair<String, String> demoPair = Pair.of("hello", "world");// 获取System.out.println("Key:" + demoPair.getKey());System.out.println("Value:" + demoPair.getValue());// 左右获取System.out.println("Left:" + demoPair.getLeft());System.out.println("Right:" + demoPair.getRight());// 更新值 会抛出异常.demoPair.setValue("123");}
}
  • 测试结果
Key:hello
Value:world
Left:hello
Right:world
Exception in thread "main" java.lang.UnsupportedOperationExceptionat org.apache.commons.lang3.tuple.ImmutablePair.setValue(ImmutablePair.java:100)at com.yanxml.util.pair.demo.PairInstanceDemo2.main(PairInstanceDemo2.java:24)

通过测试结果我们可以发现. 此Pair类, 除了声明的方式不同外, 其与原生的Pair毫无区别.
并且, 我们试图修改Pair内的对象时, 还会抛出异常.

org.apache.commons.lang3.tuple.Pair 源码解析

  • org.apache.commons.lang3.tuple.Pair
    在这里插入图片描述
  • org.apache.commons.lang3.tuple.ImmutablePair
    在这里插入图片描述
    下面我们分别看下源码. 会看到一个非常有意思的地方.
package org.apache.commons.lang3.tuple;import java.io.Serializable;
import java.util.Map.Entry;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;public abstract class Pair<L, R> implements Entry<L, R>, Comparable<Pair<L, R>>, Serializable {private static final long serialVersionUID = 4954918890077093841L;public Pair() {}public static <L, R> Pair<L, R> of(L left, R right) {return new ImmutablePair(left, right);}public abstract L getLeft();public abstract R getRight();public final L getKey() {return this.getLeft();}public R getValue() {return this.getRight();}public int compareTo(Pair<L, R> other) {return (new CompareToBuilder()).append(this.getLeft(), other.getLeft()).append(this.getRight(), other.getRight()).toComparison();}public boolean equals(Object obj) {if (obj == this) {return true;} else if (!(obj instanceof Entry)) {return false;} else {Entry<?, ?> other = (Entry)obj;return ObjectUtils.equals(this.getKey(), other.getKey()) && ObjectUtils.equals(this.getValue(), other.getValue());}}public int hashCode() {return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^ (this.getValue() == null ? 0 : this.getValue().hashCode());}public String toString() {return "" + '(' + this.getLeft() + ',' + this.getRight() + ')';}public String toString(String format) {return String.format(format, this.getLeft(), this.getRight());}
}
package org.apache.commons.lang3.tuple;public final class ImmutablePair<L, R> extends Pair<L, R> {private static final long serialVersionUID = 4954918890077093841L;public final L left;public final R right;public static <L, R> ImmutablePair<L, R> of(L left, R right) {return new ImmutablePair(left, right);}public ImmutablePair(L left, R right) {this.left = left;this.right = right;}public L getLeft() {return this.left;}public R getRight() {return this.right;}public R setValue(R value) {throw new UnsupportedOperationException();}
}

在Pair方法内, 我们可以看到其构造函数主要有2个.

# Pair 类public Pair() {}public static <L, R> Pair<L, R> of(L left, R right) {return new ImmutablePair(left, right);}# ImmutablePair 类
public final class ImmutablePair<L, R> extends Pair<L, R> {private static final long serialVersionUID = 4954918890077093841L;public final L left;public final R right;public static <L, R> ImmutablePair<L, R> of(L left, R right) {return new ImmutablePair(left, right);}public ImmutablePair(L left, R right) {this.left = left;this.right = right;}}

其实我们经常使用的Pair.of(), 真实的实例化使用的是ImmutablePair, 也就是不可变的Pair类. 这也解释了为什么我们在执行set方法时, 会抛出异常.

# ImmutablePair 类 中public R setValue(R value) {throw new UnsupportedOperationException();}

还有一处比较有意思的一点是, 这个Pair类, 虽然提供了set方法, 但是执行此方法, 会给我们抛出异常. 这也是我们之前测试代码中的相关异常.


总结

本章, 主要介绍了2种Pair类的相关使用方式, 并且查看了相关源码. 我们可以得出如下差异点:

共同点
  • 使用泛型进行定义. class Pair<K,V>, 这样可以体现泛型的好处, 容易扩展.
  • 定义后的Pair内, 只有get方法, 而无set方法.
不同点
  • 声明对象的方式有所不同. 其实本质并无差别.
    • Java原生的Pair类, 需使用new Pair<K,V> (key,value)这样的方式进行声明.
    • Lang3的Pair类, 常使用Pair.of(key,value)进行声明.
  • Lang3的Pair类, 除getKey/getValue 方法外, 会额外提供 getLeft/getRight 这一对方法.

Reference

[源码] [javafx.util.Pair]
[源码] [org.apache.commons.lang3.tuple.Pair]

这篇关于[Java基础] 2个Pair工具类比较的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/988153

相关文章

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件