A set has only one type parameter, which represents its element type, and a map has two type parameters that represent its key and value type.
However, there are times when you need more flexibility, such as a database row with any number of columns, and you want to be able to access all the columns in a type-safe manner. The method is to parameterize the key instead of parameterization the container, and then submit the parameterized key to the container to insert or get the value. Use a generic system to ensure that the type of the value matches its key.
Example:
Public classFavorites {PrivateMap<class<?>, object> favorites =NewHashmap<class<?>, object>(); Public<T>voidPutfavorites (class<t>type, T instance) { if(Type = =NULL) Throw NewNullPointerException (); Favorites.put (Type, Type.cast (instance)); } Public<T> T getfavorites (class<t>type) { returntype.cast (Favorites.get (type)); }}
The class object acts as a part of the parameterized key, starting with java1.5, where the type is no longer a simple class, but a class<t>. When the literal literal of a class is used in a method to convey the type information at compile time and run time, it is called type token, type token.
Inspection code:
New Favorites (); F.putfavorites (String. class, "Java"); F.putfavorites (Integer. class, 123); System.out.println (F.getfavorites (String. class )); System.out.printf ("%x", F.getfavorites (Integer. ) Class));
29th: Prioritize type-safe heterogeneous containers