JAVA makes use of object methods with different generic return types

  • 2020-06-12 08:56:55
  • OfStack

While it is sometimes necessary to return objects of different types at the end of a method, the return statement can only return one or a group of objects of type 1. This is where generics come in.

First of all, to explain the concept,

Tuple: A single 1 object that packages a set of objects directly into a container that allows the elements to be read, but not modified.

Create tuples with generics


public class ReturnTwo<A,B> {

 public final A first;
 public final B second;

 public ReturnTwo(A a,B b) {
  first = a;
  second = b;
 }

}

test


public class Test {

 private String a = "abc";
 private int b = 123;

 public ReturnTwo<String, Integer> get() {
  ReturnTwo<String, Integer> rt = new ReturnTwo<String, Integer>(this.a, this.b);
  return rt;
 }

 public static void main(String[] args) {
  Test test = new Test();
  ReturnTwo<String, Integer> rt = test.get();
  System.out.println(rt.first);
  System.out.println(rt.second);
 }

}

Output results:

abc
123


Related articles: