[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
详解
通过结构, 我们可以发现. 这个类就这些基本成员和方法. 其中最主要的就是 构造函数
getKey
和 getValue
这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)
进行声明.
- Java原生的Pair类, 需使用
- Lang3的Pair类, 除
getKey/getValue
方法外, 会额外提供getLeft/getRight
这一对方法.
Reference
[源码] [javafx.util.Pair]
[源码] [org.apache.commons.lang3.tuple.Pair]
[Java基础] 2个Pair工具类比较相关推荐
- Java基础教程:JavaArrays工具类
Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承.指针等概念.Java不但可以用来开发网站后台.PC客户端和AndroidAPP,还在数据分析.网络爬虫 ...
- JAVA基础知识之Collections工具类
排序操作 Collections提供以下方法对List进行排序操作 void reverse(List list):反转 void shuffle(List list),随机排序 void sort( ...
- (转)JAVA 十六个常用工具类
(转)JAVA 十六个常用工具类 一. org.apache.commons.io.IOUtils closeQuietly 关闭一个IO流.socket.或者selector且不抛出异常.通常放在f ...
- Java基础学习——第十章 枚举类注解
Java基础学习--第十章 枚举类&注解 一.枚举类(enum) 1. 枚举类的概念 枚举类:类的对象只有有限个,确定的 线程状态:创建.就绪.运行.阻塞.死亡 当需要定义一组常量时,强烈建议 ...
- java inputtools_Java后台开发常用工具类
本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数据库连接.格式转换.文件操作.发送邮件等等.提高开发效率,欢迎收藏与转载. 数据库连接工具类 数据库连接工具类--仅仅获得连接对象 ...
- java 兼容excel_Java解析Excel工具类(兼容xls和xlsx)
依赖jar org.apache.poi poi-ooxml 4.0.1 ExcelUtils.java package javax.utils; import java.io.File; impor ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
- 【java笔记】Collections集合工具类
java.utils.Collections是集合工具类,用来对集合进行操作 常用方法: public static<T>boolean addAll(Collection<T> ...
- JAVA实现 PDF转换 常用工具类(html转PDF、PDF添加页码、PDF文件下载、PDF添加印章或者水印)
JAVA实现 PDF转换 常用工具类(html转PDF.PDF添加页码.PDF文件下载.PDF添加印章或者水印)可直接使用 package com.bestvike.util; import com. ...
最新文章
- 从阿里云下载图片到本地
- 程序设计基础c语言上机考试,C语言程序设计基础上机考试一题目及参考答案..doc...
- python的特征提取实验一_在opencv3中使用ORB进行特征提取实验-Python版
- php 检测编码函数,自己写了一个php检测文件编码的函数
- 扇区 修复 linux,linux – 如何使用hdparm来修复挂起的扇区?
- 耳挂式蓝牙耳机原理_耳挂式蓝牙耳机项目总结分析报告
- python基础之列表、元组
- Android面试简历
- 佳博GP1124T的安装向导
- 如何解决网站不安全信息?免费SSL证书
- ZigBee学习之NXP JN5169开发环境搭建
- c语言if的作用,c语言if语句的用法
- 配音秀 v8.10.255
- win10锁屏幻灯片放映不能播放幻灯片问题的一种解决办法
- Win7/windows8/win 10系统下Photoshop不能直接拖拽打开图片的解决办法
- Web——软件开发实践
- 谈谈未来 APP 产品设计的革命性趋势
- 如何设置STM32的系统时钟(SYSCLK)
- ADB读取和备份安卓应用数据(无Root)
- 安卓开发实战讲解!首发10万字Android开发实战文档,完整版开放下载
热门文章
- C#一个完整的Log4net使用实例
- 五月&六月券商金工精选
- PPPOE拨号之三:H3C路由器PPPoE典型配置【包括服务器与client PAP CHAP等方式】
- 如何用jconsole连接远程的springboot程序?(实测可行,网上其他的有点问题)
- 打印机显示服务器脱机是什么原因,“打印机显示脱机无法打印的解决办法”的解决方案...
- 提高总账和日记账导入的性能
- 程浩阐述AI创业的五个关键问题 透露新投资项目
- 企业数字化转型全是坑?这几篇数字化转型成功案例,减少70%损失
- Hyperchain超块链创始人史兴国:“数藏云” 助力实体数字化转型
- Android 通过开源框架实现加载网络图片并下载到SD卡通知系统相册显示,(并实现分享图片功能)