[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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2