[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

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap