Languages
[Edit]
EN

Java - create generic pair (tuples, point)

1 points
Created by:
Geo-Baby
240

Quick solution:

public class Pair<A, B> {
    private final A a;
    private final B b;

    public Pair(A a, B b) {
        this.a = a;
        this.b = b;
    }

    public A getA() {
        return a;
    }

    public B getB() {
        return b;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "a=" + a +
                ", b=" + b +
                '}';
    }

    public static void main(String[] args) {
        {
            Pair<String, String> pair = new Pair<>("A", "B");
            String a = pair.getA();
            String b = pair.getB();
            System.out.println(pair); // Pair{a=A, b=B}
        }

        {
            Pair<Double, Double> pair = new Pair<>(0.2, 3.14);
            Double a = pair.getA();
            Double b = pair.getB();
            System.out.println(pair); // Pair{a=0.2, b=3.14}
        }

        {
            Pair<Integer, Integer> pair = new Pair<>(10, 25);
            Integer a = pair.getA();
            Integer b = pair.getB();
            System.out.println(pair); // Pair{a=10, b=25}
        }

        {
            Pair<Pair<Integer, Integer>, Pair<String, String>> pair
                    = new Pair<>(new Pair<>(10, 25), new Pair<>("A", "B"));
            Pair<Integer, Integer> a = pair.getA();
            Pair<String, String> b = pair.getB();
            System.out.println(pair); // Pair{a=Pair{a=10, b=25}, b=Pair{a=A, b=B}}
        }
    }
}

Output:

Pair{a=A, b=B}
Pair{a=0.2, b=3.14}
Pair{a=10, b=25}
Pair{a=Pair{a=10, b=25}, b=Pair{a=A, b=B}}

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join