29th: Prioritize type-safe heterogeneous containers

Source: Internet
Author: User

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<?&gt, 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.