Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Pair in Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand Pair in Java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand Pair in Java".

Catalogue

1 Pair usage

2 Pair source code

3 ImmutablePair source code

4 MutablePair source code

5 questions?

Foreword:

Pair in Java accidentally found that Pair was used in the project during the development process. I thought it was interesting that I had never encountered this thing before, so I wrote it down.

When we write code, we will definitely encounter two values to be returned, but both values are useful, so we usually use the map collection for key-value encapsulation, or write a class to encapsulate two properties to return, but although these two ways are simple to implement, they feel a bit wasteful or unattractive. If a large number of such values occur, create a large number of classes or map collections. To solve this problem, a powerful utility class-pair, which is under the org.apache.commons.lang3.tuple package.

1 Pair usage

Let's first take a look at the usage of Pair:

@ Test public void TestPair () {Pair pair = Pair.of ("left", "right"); System.out.println ("left =" + pair.getLeft ()); System.out.println ("right =" + pair.getRight ()); System.out.println ("key =" + pair.getKey ()); System.out.println ("value =" + pair.getValue ()) Pair mutablePair = new MutablePair ("left", "right"); System.out.println ("- mutablePair----"); System.out.println ("left =" + pair.getLeft ()); System.out.println ("right =" + pair.getRight ()) System.out.println ("key =" + pair.getKey ()); System.out.println ("value =" + pair.getValue ()); Pair immutablePair = new ImmutablePair ("left", "right"); System.out.println ("- immutablePair----") System.out.println ("left =" + pair.getLeft ()); System.out.println ("right =" + pair.getRight ()); System.out.println ("key =" + pair.getKey ()); System.out.println ("value =" + pair.getValue ());}

The above is a relatively simple column, let's take a look at the printed results:

The above is the printed result, where MutablePair,ImmutablePair is a subclass of pair, so it is easy to use, and there is no need to define additional map collections and classes to encapsulate.

2 Pair source code

In fact, the source code is relatively simple. The Pair source code is as follows:

/ Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler) / / package org.apache.commons.lang3.tuple;import java.io.Serializable;import java.util.Objects;import java.util.Map.Entry;import org.apache.commons.lang3.builder.CompareToBuilder;public abstract class Pair implements Entry, Comparable, Serializable {private static final long serialVersionUID = 4954918890077093841L Public Pair () {} / / defaults to the subclass ImmutablePair, public static Pair of (L left, R right) {return new ImmutablePair (left, right);} / defines the abstract method, and the target subclass implements public abstract L getLeft (); / / defines the abstract method, and the target subclass implements public abstract R getRight () / / to get key here is to get the value of getLeft () method public final L getKey () {return this.getLeft ();} / / to get value here is to get the value public R getValue () {return this.getRight () of getRight () method. } / / this is to compare two Pair public int compareTo (Pair 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 Objects.equals (this.getKey (), other.getKey ()) & & Objects.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 ());}}

The above source code simply defines our regular methods, the getLeft () and getRight () methods are left to the subclass to implement, the parent class defaults to the ImmutablePair subclass, Pair also implements Entry, and you can use getKey () and getValue (). In fact, they both call the getLeft () and getRight () methods, inherit Comparable, and compare the two Pair. Inherits Serializable and can be serialized.

3 ImmutablePair source code

Let's look at the ImmutablePair source code:

/ Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler) / / package org.apache.commons.lang3.tuple;// inherits Pairpublic final class ImmutablePair extends Pair {private static final ImmutablePair NULL = of ((Object) null, (Object) null); private static final long serialVersionUID = 4954918890077093841L; / / modified by final, the left value is set to immutable public final L left / final is used here. After the rightvalue is set, the immutable public final R right; public static ImmutablePair nullPair () {return NULL;} public static ImmutablePair 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;} / / because it is an immutable value, public R setValue (R value) {throw new UnsupportedOperationException ();}} is thrown if the set value is immutable.

The ImmutablePair source code is simple, but the variables are modified with final and are immutable, so when the setValue () method is called, an exception is thrown: UnsupportedOperationException.

4 MutablePair source code

The MutablePair source code is as follows:

/ Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler) / / package org.apache.commons.lang3.tuple;public class MutablePair extends Pair {private static final long serialVersionUID = 4954918890077093841L; public L left; public R right; public static MutablePair of (L left, R right) {return new MutablePair (left, right);} public MutablePair () {} public MutablePair (L left, R right) {this.left = left This.right = right;} public L getLeft () {return this.left;} public void setLeft (L left) {this.left = left;} public R getRight () {return this.right;} public void setRight (R right) {this.right = right } / / the set value here, which returns the old value public R setValue (R value) {R result = this.getRight (); this.setRight (value); return result;}}

The difference between the above MutablePair source code and the ImmutablePair source code is that MutablePair is variable and ImmutablePair is immutable.

5 questions?

If you want to return more than 2, 3 how to do?

No problem, as for you, the Triple class for building three elements is provided in this org.apache.commons.lang3.tuple package, abstract class Triple in the class definition. The definition of three generics also provides a pair of immutable and mutable implementation classes for ImmutableTriple and MutableTriple, and the source code is similar to the one above, but with an additional variable attribute.

If there are 4 normal parameters and 5 normal parameters, I'm sorry, you can only return by defining bean encapsulation or map collection.

Thank you for your reading, the above is the content of "how to understand Pair in Java". After the study of this article, I believe you have a deeper understanding of how to understand Pair in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report