Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Triplet Class ใน JavaTuples

Triplet Class เป็น Tuple ของ 3 Elements เป็นส่วนหนึ่งของ JavaTuples Library

ต้อง Import Package:

import org.javatuples.Triplet;

ตัวอย่างที่ 1: สร้าง Triplet

import org.javatuples.Triplet;

public class Demo {
    public static void main(String[] args) {
        Triplet<String, String, String> t = new Triplet<String, String, String>("One", "Two", "Three", "Four", "Five");
        System.out.println(t);
    }
}

ผลลัพธ์

[One, Two, Three, Four, Five]

หมายเหตุ: โค้ดต้นฉบับส่ง 5 Arguments ให้ Triplet<String,String,String> ซึ่งผิด (Triplet ควร 3 Elements) อาจเป็น Typo ในตัวอย่าง

ตัวอย่างที่ 2: Get Value จาก Triplet

import org.javatuples.Triplet;

public class Demo {
    public static void main(String[] args) {
        Triplet<String, String, String> t = new Triplet<String, String, String>("One", "Two", "Three");
        System.out.println(t);
        System.out.println("Get Value: " + t.getValue0());
    }
}

ผลลัพธ์

[One, Two, Three]
Get Value: One

ตัวอย่างที่ 3: Set Value และ Copy With New Value

import org.javatuples.Triplet;

public class Demo {
    public static void main(String[] args) {
        Triplet<String, String, String> t1 = Triplet.with("Movies", "Web Series", "TV Shows");
        System.out.println(t1);
        
        Triplet<String, String, String> t2 = t1.setAt1("Songs");  // Copy แล้วเปลี่ยน Index 1
        System.out.println(t2);
    }
}

ผลลัพธ์

[Movies, Web Series, TV Shows]
[Movies, Songs, TV Shows]

เมธอดสำคัญ: with() Factory Method, getValue0()/1()/2() ดึงค่า, setAt0()/1()/2() คืน Tuple ใหม่ที่เปลี่ยนค่าแล้ว (Immutable)