【JAVA】【集合19】Java中的Pair


16.【集合】Pair

一、Pair定義

當一個方法需返回兩個值、並且兩個值都有重要意義時,我們一般會用Map的key、value來表達。但是如果僅返回兩個值,就用管理一堆key/value鍵值對的HashMap等結構,有點大材小用,增加了數據結構的復雜度。

在javafa.util包中,定義了Pari(配對)結構,可以用來表達此種情況。請定義如下:

public class Pair<K,V> implements Serializable{ 
    private K key;    
    private V value;
    ....
}

二、主要方法

1、構造方法

    public Pair(@NamedArg("key") K key, @NamedArg("value") V value) {
        this.key = key;
        this.value = value;
    }

2、查詢方法

    public K getKey() { return key; }
    public V getValue() { return value; }

3. 比較方法

     public 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<String, String> pair = new Pair<>("aku", "female");     
pair.getKey();     
pair.getValue(); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM