Java in generalization

JDK1.5 version is available in a generic concept, in essence, is the programmer-defined generic type-safe, in the absence of generics provide, Java also provides a reference to Object "arbitrary" of the operation, any of this operation is carried out "downcast" and "transformation up" operation on the Object reference, but some of the cast of the error may not be caught compiler, there are all cast completely hidden, thus providing a generic mechanism.

I. Review of "transformation up" and "downcast"

To review by the following example:

public class Test {
	private Object b;
	public Object getB() {
		return b;
	}
	public void setB(Object b) {
		this.b = b;
	}
	public static void main(String args[]) {
		Test t =new Test();
		t.setB(new Boolean(true));
		System.out.println(t.getB());
		t.setB(new Float(3.14));
		Float f = (Float)(t.getB());
		System.out.println(f);
	}
}
/*输出结果如下:
true
3.14
*/

In the above example, the Test class defines a private member variable B, which is of type Object type, while its corresponding setXXX first round () and getXXX () methods. In the main class method, new Boolean (true) object as set B () method parameters, since the parameter type set B () method to make Object, thus achieving a "up" transformation. At the same time when you call getB () method, the Object object getB () method returns the corresponding return type, which is "downcast."

 

Second, the definition of generic

Object class is the topmost parent class, many programmers in order to make the program more versatile. Usually the value passed in the design of the program and return values ​​are dominated by the Object type. When you need to use these instances, the instance must be properly converted to the original type, otherwise will occur at runtime ClassCastException anomaly.

Generics syntax is as follows:

类名<T>
//T代表一个类型的名称

Define a generic be described by the following examples:

public class OverClass<T> {
	private T over;
	public T getOver() {
		return over;
	}
	public void setOver(T over) {
		this.over = over;
	}
	public static void main(String args[]) {
		OverClass<Boolean> over1 = new OverClass<Boolean>();
		OverClass<Float> over2 = new OverClass<Float>();
		over1.setOver(true);
		over2.setOver(3.14f);
		Boolean b = over1.getOver();
		Float f = over2.getOver();
		System.out.println(b);
		System.out.println(f);
	}
}
/*输出结果如下:
true
3.14
*/

 

Third, the conventional usage of generics:

1, a plurality of statements defining a generic class type

The syntax is as follows:

MutiOverClass<T1,T2>
//MutiOverClass:泛型类名称

Wherein, T1 and T2 are possible types are defined.

This can be specified when a plurality of types of specified object instance of the type, for example:

MutiOverClass<Boolean,Float> = new MutiOverClass<Boolean,Float>();

2, when the array type declarations define a generic class

Examples are as follows:

public class ArrayClass<T> {
	public T[] array;
	public void SetT(T[] array) {
		this.array = array;
	}
	public T[] getT() {
		return array;
	}
	public static void main(String args[]) {
		ArrayClass<String> a = new ArrayClass<String>();
		String[] array = {"成员1","成员2","成员3"};
		a.SetT(array);
		for(int i=0;i<a.getT().length;i++) {
			System.out.println(a.getT()[i]);
		}
	}
}
/*输出结果如下:
成员1
成员2
成员3
*/

Visible through the above-described examples, can be declared in a generic mechanism to use an array, but can not be used to create an instance of a generic array, for example, the following code is wrong:

public class ArrayClass<T>{
    private T[] array = new T[10];
}

3, elements of the collection container class declaration

Character K and V may be used on behalf of the container in two specific keys and key values ​​corresponding to, for example:

public class TestClass<K,V> {
	public Map<K, V>m = new HashMap<K, V>();
	public void put(K k,V v) {
		m.put(k, v);
	}
	public V get(K k) {
		return m.get(k);
	}
	public static void main(String[] args) {
		TestClass<Integer, String> tc = new TestClass<Integer, String>();
		for(int i=0;i<5;i++) {
			tc.put(i,"集合成员:"+i);
		}
		for(int i=0;i<tc.m.size();i++) {
			System.out.println(tc.get(i));
		}
	}
}
/*输出结果如下:
集合成员:0
集合成员:1
集合成员:2
集合成员:3
集合成员:4
*/

There are many generalized set has a frame, it can be directly in the main process public Map <K, V> m = new HashMap <K, V> () in Java; statement created instance, and then calls the appropriate interface Map the put () and get () method of filling containers complete set of functions or obtaining specific values ​​on the keys, are used when several of the following generic collection with:

It is commonly used generic collection with
Collections Generic definitions
ArrayList ArrayLiset<E>
HashMap HashMap<K,V>
HashSet HashSet<E>
Vector Vector<E>


 

 

 

 

 

 

Examples are as follows:


public class AnyClass {
	public static void main(String args[]) {
		ArrayList<Integer> a = new ArrayList<Integer>();
		a.add(1);
		for(int i=0;i<a.size();i++) {
			System.out.println("获取ArrayList容器的值:"+a.get(i));
		}
		Map<Integer, String> m = new HashMap<Integer, String>();
		for(int i=0;i<5;i++) {
			m.put(i,"成员:"+i);
		}
		for(int i=0;i<m.size();i++) {
			System.out.println("获取Map容器的值:"+m.get(i));
		}
		Vector<String> v = new Vector<String>();
		for(int i=0;i<5;i++) {
			v.addElement("成员"+i);
		}
		for(int i=0;i<v.size();i++) {
			System.out.println("获取Vector容器的值:"+v.get(i));
		}
	}
}
/*输出结果如下:
获取ArrayList容器的值:1
获取Map容器的值:成员:0
获取Map容器的值:成员:1
获取Map容器的值:成员:2
获取Map容器的值:成员:3
获取Map容器的值:成员:4
获取Vector容器的值:成员0
获取Vector容器的值:成员1
获取Vector容器的值:成员2
获取Vector容器的值:成员3
获取Vector容器的值:成员4
*/

Fourth, the generalization of advanced usage:

1, can be used to limit the generic type

The default may use any type to instantiate a generic class object, but also Java generic class type for example of the wrong limits syntax is as follows:

class 类名称<T extends anyClass>
//anyClass:某个接口或类

After restricting the use of generics, generic type or class must implement this interface inherits anyClass or class. Whether anyClass is an interface or class, must use extends keyword during generics limit, for example:

public class LimitClass<T extends List> {
	public static void main(String[] args) {
		LimitClass<ArrayList> l1 = new LimitClass<ArrayList>();
		LimitClass<LinkedList> l2 = new LimitClass<LinkedList>();
		//下面这句时错误的,因为HashMap没有实现List()接口
        LimitClass<HashMap> l3 = new LimitClass<HashMap>();
	}
}

2, the type of use wildcards

In the generic mechanism provided a wildcard type, whose main role is to limit this type of generic classes or subclasses implement an interface or class when creating a generic class object, to declare such an object can be used. " ? "wildcards to represent, at the same time use extends keyword to restrictions on generics syntax is as follows:

泛型类名称<? extends List>a = null;

3, inheritance and generic class implement generic interface

Examples are as follows:

public class ExtendClass<T1> {
}
class SubClass<T1,T2,T3>extends ExtendClass<T1>{
}

If you leave the generic type of the parent class when the class inherits ExtendClass SubClass classes, inheritance need to specify when, if not specified, directly extends ExtendClass statement inheriting class SubClass sheets T1, T2 and T3 are automatically becomes Object, All will remain a generic type of parent class in general.

5, generic summary

Generic used as follows:

(1) only when the generic type parameter class type, not a simple type

(2) The number of types may be a plurality of generic

(3) can be used to limit the generic type extends keyword

(4) may be used to limit the generic type wildcards
 

发布了61 篇原创文章 · 获赞 1 · 访问量 1318

Guess you like

Origin blog.csdn.net/qq_29440983/article/details/103952345