- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 296字
- 2021-07-02 19:01:55
Generics
Generics were introduced in Java 1.5. Generics help the user to create the general purpose code that has abstract type in its definition. That abstract type can be replaced with any concrete type in the implementation.
For example, the list interface or its implementations, such as ArrayList, LinkedList and so on, are defined with generic type. Users can provide the concrete type such as Integer, Long, or String while implementing the list:
List<Integer> list1 =new ArrayList<Integer>(); List<String> list2 =new ArrayList<String>();
Here, list1 is the list of integers and list2 is the list of strings. With Java 7, the compiler can infer the type. So the preceding code can also be written as follows:
List<Integer> list1 =new ArrayList<>(); List<String> list2 =new ArrayList<>();
Another huge benefit of generic type is that it brings compile-time safety. Let's create a list without the use of generics:
List list =new ArrayList<>();
list.add(1);
list.add(2);
list.add("hello");
list.add("there");
Here, you can see that the list contains both integers and strings. If you retrieve an element of it, it will be of an object type by default:
Object object = list.get(0);
So the user has to specifically cast it to its correct type:
Integer object = (Integer)list.get(0);
This makes the code error prone. Because if casting is done correctly, it will throw ClassCastException at runtime. Let's create the same list with the use of generics:
List<Integer> listGeneric =new ArrayList<>(); listGeneric.add(1); listGeneric.add(2); listGeneric.add("hello"); // won't compile
listGeneric becomes the list of integers. If you try to add strings in it, the compiler will not allow it.
So, now if you retrieve an element from the list, it will give you an integer type. No type casting is required, which will save us from ClassCastException at runtime. Hence, it provides compile-time safety:
Integer intObject = listGeneric.get(0);
- 軟件安全技術(shù)
- UML+OOPC嵌入式C語言開發(fā)精講
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- 深入淺出DPDK
- Full-Stack React Projects
- Serverless computing in Azure with .NET
- Bootstrap 4 Cookbook
- Akka入門與實(shí)踐
- Hands-On Dependency Injection in Go
- After Effects CC案例設(shè)計與經(jīng)典插件(視頻教學(xué)版)
- HTML5游戲開發(fā)實(shí)戰(zhàn)
- C Primer Plus(第6版)中文版【最新修訂版】
- Unity虛擬現(xiàn)實(shí)開發(fā)圣典
- Flink原理深入與編程實(shí)戰(zhàn):Scala+Java(微課視頻版)
- Vue.js項(xiàng)目開發(fā)實(shí)戰(zhàn)