Sometimes we have a container with only one type or several types that do not satisfy our requirements, such as the type of elements stored in set are the same, and the map specifies two
Here we can parameterize the key, instead of the container parameterization, that is, we can give the container a key type, and then value to put the corresponding instance, so that can be stored in a number of different types
Such as:
Packagecn.xf.cp.ch02.item29;ImportJava.util.HashMap;ImportJava.util.Map; Public classmanytypeclass{//a container that holds data, because the type of the key value is indeterminate, then the value type can only be an object type PrivateMap<class<?>, object> data =NewHashmap<class<?>, object>(); Public<T>voidPutData (class<t>type, T instance) { //Let's put the data in. if(Type! =NULL) { //there is a need for a type conversion, through the class's cast method, because the generic is based on erasure, and if not validated, then the type of the data being inserted is not really OK .data.put (Type, Type.cast (instance)); } } Public<T> T getDate (class<t>type) { //Take out the data, because the data is stored in the type of object, then you need to do a type conversion returntype.cast (Data.get (type)); } Public Static voidMain (string[] args) {Manytypeclass MTC=NewManytypeclass (); Mtc.putdata (String.class, "Cutter_point"); Mtc.putdata (Integer.class, 0XCAB145DE); Mtc.putdata (Class.class, Manytypeclass.class); Mtc.putdata (Manytypeclass.class, MTC); String datastring= Mtc.getdate (String.class); intDatainteger = Mtc.getdate (Integer.class); Class<?> DataClass = Mtc.getdate (Class.class); Manytypeclass MTC1= Mtc.getdate (Manytypeclass.class); System.out.printf ('%s%x%s%s%n ', Datastring, Datainteger, Dataclass.getname (), Mtc1.getdate (String.class)); }}
Run Display results:
Heterogeneous success, this class can hold a variety of different types, but be careful not to put list<string> type or list<integer> type, because first list<string>.class is not legal, Then even if you put a list in, if the data stored in the different, key is a list, the result is placed in the list<integer> type, the results are not satisfied, that is, can not be used in non-materialized types. You can save a String or string[] but cannot compile if it is a list<string> type
"Effective Java" 8, preferred type-safe heterogeneous containers