What is Yuanzu
java Methods in can only return a single object , What if you need to return more than one ? Usually we create an extra object , Or put the returned content into the collection to return , in addition , We also have other options : Combine generics , We can package a set of objects directly into a single object , Then read the element from the object , And can clearly know the type of each element , Use them safely .
This concept is called tuple , Also known as Data transmission object ( namely DTO) or messenger .
Usually , Tuples can have any length , Objects in tuples can be of different types . however , We want to be able to specify the type for each object , And read from tuples , Can get the right type . To deal with different lengths , We need to create multiple different tuples . Here's a tuple that can store two objects :
public class Tuple2<A, B> {
public final A a1;
public final B a2;
public Tuple2(A a, B b) { a1 = a; a2 = b; }
}
public and final The combination of elements ensures the readability and immutability of elements . The type composition of the ancestor object depends on the order in which the parameters are passed .
We can use inheritance to achieve a longer Yuanzu :
public class Tuple3<A, B, C> extends Tuple2<A, B> {
public final C a3;
public Tuple3(A a, B b, C c) {
super(a, b);
a3 = c;
}
}
public class Tuple4<A, B, C, D> extends Tuple3<A, B, C> {
public final D a4;
public Tuple4(A a, B b, C c, D d) {
super(a, b, c);
a4 = d;
}
}
When using tuples , You just need to define a tuple of the right length , Take it as the return value . Notice the return type of the method in the following example :
public class TupleTest {
static Tuple2<String, Integer> f() {
// 47 Automatic packing is Integer
return new Tuple2<>("hi", 47);
}
static Tuple3<Student, String, Integer> g() {
return new Tuple3<>(new Student(), "hi", 47);
}
}
Use type parameters to infer , We can create a number of overloaded static generic methods to omit new Cumbersome operation :
public class Tuple {
public static <A, B> Tuple2<A, B> tuple(A a, B b) {
return new Tuple2<>(a, b);
}
public static <A, B, C> Tuple3<A, B, C>
tuple(A a, B b, C c) {
return new Tuple3<>(a, b, c);
}
}
public class TupleTest {
static Tuple2<String, Integer> f() {
return tuple("hi", 47);
}
static Tuple3<Student, String, Integer> g() {
return tuple(new Student(), "hi", 47);
}
}