In this article, we'll discuss a few new language features in JDK1.5, including:
Generics (generics)--Provides compile-time type safety for a collection (collections) and casts a cast (cast) without getting an object from collections every moment
Enhanced ' for ' loop (enhanced for loop)--Reduces potential errors in iterators (iterator) (error-proneness)
Automatic placement/automatic removal (autoboxing/unboxing)-eliminates the need to manually convert between the base type (primitive types) (for example, double) and the wrapper type (wrapper types) (for example, double).
Type-Safe Enumeration (Typesafeenums)-provides the benefits of a type-safe enumeration pattern.
Static Import--there is no need to prefix its class name with static member variables of other classes. This will make the code more concise.
Metadata (Metadata)--enables programmers to avoid writing boilerplate code (boiler plate codes) and provides an opportunity to design declarative programming (declarative programming).
Let's discuss each new feature in detail and see some examples.
Generics (generics)
Generics are one of the most "cool" features in JDK1.5. By introducing generics, we get the security of the compile-time type and the possibility of the runtime throwing classcastexceptions more small. In JDK1.5, you can declare the type of object that a collection will receive/return. In JDK1.4, creating an employee's Name list (list) requires a collection object, like the following statement:
List listofemployeename = new ArrayList ();
In JDK1.5, you will use the following statement
List listofemployeename = new ArrayList ();
The "cool" thing is that if you try to insert a value that is not a string type, you will find it at compile time and fix the problem. Without generics, you'll find such a bug that when your client calls, it tells you that the program you're writing is throwing a classcastexception exception and crashing.
In addition, you do not need to cast when you get an element from the collection. So it was originally:
String EmployeeName = ((string) listofemployee.get (i));
The following statement will be simpler than the above:
String EmployeeName = Listofemployee.get (i);