20 minutes, familiar with Tiger Tigers - New Features Introduction

xiaoxiao2021-03-06  60

An important topic of "JDK1.5" (development code tiger) is to simplify development by adding some features, including generics, for-Each cycles, automatic packages / unpacking, enumeration, variable parameters, static Import. Use these features help we write more clear, fine, safe code. Let's take a brief introduction to these new features. 1. Generic C can specify a collection of element types by template technology, while Java has no corresponding function before 1.5. A collection can place any type of object, and we have to enforce the type conversion from the item from the collection. Tiger introduces generics, which allows you to specify the type of elements in the collection so that you can get the benefits of type checking at compile time. Collection C = New ArrayList (); C.Add (New Date ()); Compiler gives an error, add (java.lang.string) in java.util.collection cannot beapplied to (java.util.date 2. 2.For-Each Cycle For-Each Cycles to join the traversal of the collection. Suppose we want to traverse a collection of elements for them. 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 a void processall (MYCLASS MyObject: c) MyObject.Process ();} This code is much more clear, and avoids mandatory type conversion . 3. Autoboxing / UnboXING Auto Package / Unpacking is greatly convenient for basic type data and their packaging. Automatic packing: The basic type is automatically turned into a packaging class. (INT >> Integer) Automatic unpacking: The packaging class is automatically converted to the basic type. (Integer >> Int) Before JDK1.5, we always not store the basics for collection Type and worry, now the automatic conversion mechanism solves our problems. 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 The addition operation for INT, then INT again converts 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. Note that variable parameters must be the last parameter in the function declaration.

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

New Post(0)