Java中方法返回多个值?---- 泛型的应用

在开发的时候,总能碰到一个方法返回多个值的情形,除了将对象以入参的方式传到方法内部以外,还可以通过泛型构造元组来实现。


元组类实例

public class Tuple {
	
	public static void main(String[] args) {
		System.out.println(Tuple.create("asdf", 123));
	}

	public static <A, B> TwoTuple<A, B> create(A a, B b) {
		return new TwoTuple<A, B>(a, b);
	}

	public static <A, B, C> ThreeTuple<A, B, C> create(A a, B b, C c) {
		return new ThreeTuple<A, B, C>(a, b, c);
	}

	public static <A, B, C, D> FourTuple<A, B, C, D> create(A a, B b, C c, D d) {
		return new FourTuple<A, B, C, D>(a, b, c, d);
	}

	private static class TwoTuple<A, B> extends Tuple{
		public final A a;
		public final B b;

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

		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append("TwoTuple [");
			if (a != null)
				builder.append("a=").append(a).append(", ");
			if (b != null)
				builder.append("b=").append(b);
			builder.append("]");
			return builder.toString();
		}
	}

	private static class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
		public final C c;

		public ThreeTuple(A a, B b, C c) {
			super(a, b);
			this.c = c;
		}

		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append("ThreeTuple [");
			if (a != null)
				builder.append("a=").append(a).append(", ");
			if (b != null)
				builder.append("b=").append(b);
			if (c != null)
				builder.append("c=").append(c).append(", ");
			builder.append("]");
			return builder.toString();
		}
	}

	private static class FourTuple<A, B, C, D> extends ThreeTuple<A, B, C> {
		public final D d;

		public FourTuple(A a, B b, C c, D d) {
			super(a, b, c);
			this.d = d;
		}

		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append("FourTuple [");
			if (a != null)
				builder.append("a=").append(a).append(", ");
			if (b != null)
				builder.append("b=").append(b);
			if (c != null)
				builder.append("c=").append(c).append(", ");
			if (d != null)
				builder.append("d=").append(d).append(", ");
			builder.append("]");
			return builder.toString();
		}
	}

}


使用方法

public class Test {
	

	public static void main(String[] args) {
		Tuple t = Tuple.create("123", 1);
		System.out.println(Tuple.create("asdf", 123));
	}

}




你可能感兴趣的:(Java中方法返回多个值?---- 泛型的应用)