Generics (1)

Generics is a technology in JDK5, mainly used in compile time, and is a security technology in compile time.

1. Tuple

1. Introduction: Multiple objects can be returned with only one method call, which should be used in coding. But for the return of a method, only one object can be returned at a time. So the solution is to create an object that holds as many objects as you want to return. Every time we need this kind of scenario, we create a class to do the job.

2. Tuple: A group of objects are directly packaged and stored in a single object. It can be understood that a tuple is a container object, the container object only allows to read the elements in it, and does not allow to store new elements in it . Therefore, the members of the object are declared final.

3. The example is as follows:

package net.oschina.tkj.chapter15.tuple;

/**
 * Tuple class
 *
 * @author Freedom
 *
 * @param <A>
 * @param <B>
 */
public class TwoTuple<A, B> {

	private final A a;
	public final B b;

	public TwoTuple(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 "TwoTuple [a=" + a + ", b=" + b + "]";
	}
	
	public static void main(String[] args) {

		Red red = new Red();
		red.setAge(11);
		red.setName("Red Square");

		VmInfo vm = new VmInfo();
		vm.setVmId(1);
		vm.setVmName("POPDAS");
		vm.setVmNum(2);

		// 2-tuple
		TwoTuple<Red, VmInfo> two = new TwoTuple<Red, VmInfo>(red, vm);
		System.out.println("Tuple object: "+two);
		
		// Get the members of the tuple
		VmInfo tupleRed = two.getB();
		Red redTuple = two.getA();

		System.out.println("tupleRed:" + tupleRed);
		System.out.println("redTuple:" + redTuple);

	}

}

 

2. Generic classes simulate a simple stack

1. Code example

package net.oschina.tkj.chapter15.stack;

/**
 * Generic class, simple stack
 *
 * @author Freedom
 *
 */
public class SimpleStack<T> {

	/*
	 * Inner class is used to provide data
	 */
	private static class Node<K> {

		K item;
		Node<K> next;

		// When creating an outer class object, an inner type object is also created, which is the end sentinel
		Node() {
			this.item = null;
			this.next = null;
		}

		Node(K item, Node<K> next) {
			this.item = item;
			this.next = next;
		}

		boolean end() {
			return item == null && next == null;
		}

	}

	// When creating an outer class object, initialize an inner class object to act as an end sentinel
	private Node<T> bottom = new Node<T>();

	// add element
	public void push(T item) {
		bottom = new Node<T>(item, bottom);
	}

	// get the element
	public T pop() {
		T res = bottom.item;
		if (!bottom.end()) {
			bottom = bottom.next;
		}
		return res;
	}

	public static void main(String[] args) {

		SimpleStack<String> simple = new SimpleStack<String>();
		String str = "this is a luck dog";
		for (String s : str.split(" ")) {
			simple.push(s);
		}

		String s;
		while ((s = simple.pop()) != null) {
			System.out.print(s+" ");
		}
	}

}

 

 

The example uses the function of the end sentinel to determine when the stack is empty.

 

3. Generic method

 

1. A class can contain a parameterized method, and the class where the method is located can be a generic class or not. In short, generic methods are not necessarily related to generic classes.

 

2. Principles of using generic methods:

① The use of generic methods can replace the genericization of the entire class, and the use of generic methods is preferred;

②For the static method, the type parameter of the generic class cannot be accessed (error message: Cannot make a static reference to the non-static type T); if the static method needs to use the generic capability, it must be declared on its own method Generics (reason: Because of the parameterized type declared on the class, the object needs to be created when it is specified. For static methods, it can be called directly without creating an object. At this time, the specific type of parameterization cannot be known, so the compilation fails. ; through the method declaration, the specific generic type can be determined when the method is called)

 

Error example:

package net.oschina.tkj.chapter15.method;

public class GenerateMethods<T> {

	/*
	 * This method will report an error: Cannot make a static reference to the non-static type T
	 *static method cannot access type parameter of generic class
	 */
	public static void f(T t) {
	}

	/*
	 * The method is correct, the static method has the ability to be generic, and the generic type must be declared on its own method
	 */
	public static <K> void f1(K k) {
	}
}

 

Example of a generic method:

package net.oschina.tkj.chapter15.method;

import java.util.ArrayList;
import java.util.List;

import net.oschina.tkj.chapter15.tuple.TwoTuple;
import net.oschina.tkj.chapter15.tupleclass.Red;
import net.oschina.tkj.chapter15.tupleclass.VnfInfo;

public class GenerateMethods<T> {

	/*
	 * Non-static methods can be used directly, the generic type declared by the generic class
	 */
	public void g(T t) {
	}

	/*
	 * The following static methods need to declare generic types on their own methods
	 */
	public static <T> void f(T t) {
		System.out.println(t.getClass().getSimpleName());
	}

	public static <K, V> TwoTuple<K, V> f1(K k, V v) {
		return new TwoTuple<K, V>(k, v);
	}

	public static <T> List<T> f2(T... args) {

		List<T> list = new ArrayList<T>();
		for (T t : args) {
			list.add(t);
		}
		return list;
	}

	public static void main(String[] args) {

		// generic method
		f(new Red());

		TwoTuple<Red, VnfInfo> method = f1(new Red(), new VnfInfo());
		System.out.println("method:" + method);

		f2("a", "b", "c");
		f2(new String[] { "c", "d", "e" });
		f2(new ArrayList<String>());
		List<Object> list = f2(new Red(), new VnfInfo());
		for (Object o : list) {
			System.out.println(o);
		}
	}

}

 

As above: To be continued...

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326489680&siteId=291194637