Why use generics? How to use generics?

When you create an object in general, will determine the specific type of unknown type. When there is no generic specified, the default type is Object types, we get in the acquisition of this type is Object time, although can be cast, but may be abnormal type conversion java.lang.ClassCastException abnormal operation, such as:

public static void main(String[] args) {
//        method1();
        Map<String, Object> map = new HashMap<>();
        map.put("key1", "123");
        map.put("key2", 456);
        System.out.println((String) map.get("key1"));//123
        System.out.println((String) map.get("key2"));//java.lang.ClassCastException
    }

So that when we take the value of the map, you must use the correct type of correspondence to the strong turn, it could easily go wrong, but if you use generics can be abnormal in advance at compile exposed, such as:

 public static void main(String[] args) {
//        method1();
//        method2();
        Map<String, String> map = new HashMap<>();
        map.put("key1", "123");
        map.put("key2", 456);//编译不通过
        System.out.println((String) map.get("key1"));
        System.out.println((String) map.get("key2"));
    }

ClassCastException summary is to run during the transfer to the compile-time into a compilation fails. Avoid strong type of transfer trouble.

Of course, this is only the most basic form of usage, the first for a number of species under the generic usage total, and the use of

  • And defines the generic class containing the format: class name of the class modifiers <variable representing generic> {} public Class ArrayList <E>
  • Generic definitions and methods containing the format: Modifier <variable representative of generic> return type method name (parameter) {} public <E> void method (E e)
  • Definitions and containing generic interface format: <variable representing generic> interface modifiers interface name {} public interface <E>

 

Guess you like

Origin www.cnblogs.com/chenglei0718/p/11408911.html