JDK1.5 new feature introduction

xiaoxiao2021-03-06  20

An important topic of JDK1.5 "(Development Code Tiger) is to simplify development by adding some characteristics, including generic, for-Each cycles, automatic packages / unpacking, enumeration, variable parameters, static imports Use these features help us write more clear, fine, safe code. Let's briefly introduce these new features. 1. Generic C can specify the elements type of the collection by template technology, while Java is 1.5 There is no corresponding function. A collection can place any type of object. When we take objects in the collection, we have to enforce the type conversion for them. Tigers introduce generics, it allows the specified collection of elements Type, so you can get the benefits of a strong type in compilation time. Collection C = New ArrayList (); C.ADD (New Date ()); the compiler gives an error, add (Java. Lang.String) in java.util.collection Cannot Be Applied to (java.util.date) 2.For-Each Cycle For-Each cycle to join the traversal of the collection. Suppose we have to traverse A collection of elements in the collection. Typical code is: Void Processall (Collection C) {for (Iterator i = C.ITerator (); I.hasNext ();) {MyClass MyObject = (MyClass) I.Next (); MyObject.process ();}} Using the For-Each loop, we can rewrite the code into the code, Void Processall (MYCLASS MyObject: c) MyObject.Process ();} The code is much more clear than the above, and avoids mandatory type conversion. 3. Autoboxing / unboxing automatic package / unpacking is greatly convenient for basic type data and their packaging class. Automatic package: The basic type automatically turns into a packaging class. (INT >> INTEGER) automatic unpacking: The package class is automatically converted to the basic type. (Integer >> int) Before JDK1.5, we always pay the basic type for the collection and slamming Automatic conversion mechanism now Dueded our questions. INT A = 3; Collection C = New ArrayList (); C.Add (a); // Auto Convert to Integer.integer B = New Integer (2); C.Add (B 2); Here Integer is automatically converted first The addition operation for INT, then INT is again converted to Integer.4. Enumeration (Enums) JDK1.5 joins a new type of "class" - enumeration type. To this end, JDK1.5 introduces a new keyword ENMU. We can define an enumeration type. Public enum color {red, white, blue} can then use color mycolor = color.red. Enumeration types offer two useful static methods values ​​() and valueof (). We can use them very conveniently. For example, For (Color C: Color.Values ​​()) System.out.Println (C); 5. Variable Parameters (VARARGS) variable parameters allow programmers to declare a method of accepting variable number of parameters.

转载请注明原文地址:https://www.9cbs.com/read-41625.html

New Post(0)