File size: 1,351 Bytes
6073323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
A 'generic type' can also be defined for an 'interface class', for example:

interface Pair<T1, T2> {
    T1 getFirst();
    T2 getSecond();
}
 

Now the types can either be fixed when writing the class implementing the interfaceclass StudentPair implements Pair<Student, Student> {

    private Student s1;
    private Student s2;
    
    public StudentPair(Student s1, Student s2) {
        this.s1 = s1;
        this.s2 = s2;
    }
    
    @Override
    public Student getFirst() {
        return s1;
    }

    @Override
    public Student getSecond() {
        return s2;
    }  
}






...or also write the implementing class 'generically typed', 
in which case the type is given only when an object is created from the class:

class Tuple<T1, T2> implements Pair<T1, T2> {
    
    private T1 first;
    private T2 second;
    
    public Tuple(T1 first, T2 second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public T1 getFirst() {
        return first;
    }

    @Override
    public T2 getSecond() {
        return second;
    }
}


 

Example of using the class:
public static void main(String[] args) {
    Tuple<Integer, Double> numbers = new Tuple<>(10, 0.25);
    System.out.println(numbers.getFirst());
    System.out.println(numbers.getSecond());
}
 

The program prints:
10
0.25