1. Generic)
1.1 description
This enhances Java's type security. You can check the types of objects in the container during compilation, and do not need to convert the types at runtime. Before j2se5, you must dynamically check and convert objects in the container during runtime.
Reduce vague containers and define the types of data to be put into containers.
Arraylist <integer> listofintegers; // <type_name> is new to the syntax
Integer integerobject;
Listofintegers = new arraylist <integer> (); // <type_name> is new to the syntax
Listofintegers. Add (New INTEGER (10); // only integer type
Integerobject = listofintegers. Get (0); // do not need to convert the retrieved object
1.2 usage
Declare and instantiate generic classes:
Hashmap <string, float> Hm = new hashmap <string, float> ();
File: // the original type cannot be used.
Genlist <int> NLIST = new genlist <int> (); file: // compilation Error
J2se 5.0 currently does not support the original type as the type parameter)
Define generic interfaces:
Public interface geninterface <t> {
Void func (t );
}
Define generic classes:
Public class arraylist <itemtype> {...}
Public class genmap <t, V> {...}
Example 1:
Public class mylist <element> extends list <element>
{
Public void swap (int I, Int J)
{
Element temp = this. Get (I );
This. Set (I, this. Get (j ));
This. Set (J, temp );
}
Public static void main (string [] ARGs)
{
Mylist <string> List = new mylist <string> ();
List. Add ("hi ");
List. Add ("Andy ");
System. Out. println (list. Get (0) + "" + list. Get (1 ));
List. Swap (0, 1 );
System. Out. println (list. Get (0) + "" + list. Get (1 ));
}
}
Example 2:
Public class genlist <t> {
Private T [] elements;
Private int size = 0;
Private int length = 0;
Public genlist (INT size ){
Elements = (T []) New object [size];
This. size = size;
}
Public t get (int I ){
If (I <length ){
Return elements [I];
}
Return NULL;
}
Public void add (t e ){
If (length <size-1)
Elements [length ++] = E;
}
}
Generic method:
Public class testgenerics {
Public <t> string getstring (t obj) {file: // implements a generic method.
Return obj. tostring ();
}
Public static void main (string [] ARGs ){
Testgenerics T = new testgenerics ();
String S = "hello ";
Integer I = 100;
System. Out. println (T. getstring (s ));
System. Out. println (T. getstring (I ));
}
}
1.3 restricted Generic
Restricted generic type indicates that the value range of the type parameter is limited. the extends keyword can be used not only to declare the inheritance relationship of a class, but also to declare the restricted relationship of a type parameter. for example, we only need a list of numbers, including integers (long, integer, short) and real numbers (double, float). It cannot be used to store other types, such as strings ), that is to say, we need to restrict the value of type parameter T to the number extremely subclass. in this case, we can use the extends keyword to limit the type parameter to a number.
Example
Public class limited <t extends number> {
Public static void main (string [] ARGs ){
Limited <integer> Number; file: // correct
Limited <string> STR; file: // compilation Error
}
}
1.4 generics and exceptions
Type parameters are not allowed in catch blocks, but can be used after the throws of the method. Example:
Import java. Io .*;
Interface executor <E extends exception> {
Void execute () throws E;
}
Public class genericexceptiontest {
Public static void main (string ARGs []) {
Try {
Executor <ioexception> E = new executor <ioexception> (){
Public void execute () throws ioexception {
// Code here that may throw
// Ioexception or a subtype
// Ioexception
}
};
E.exe cute ();
} Catch (ioexception IOE ){
System. Out. println ("ioexception:" + IOE );
IOE. printstacktrace ();
}
}
}
1.5 wildcard "? "
"? "Can be used to replace any type, such as using wildcards to implement the print method.
Public static void print (genlist <?> List ){})
1.6 limitations of generics
(1) instantiation of generics
T = new T (); file: // Error
(2) arrays that can instantiate generic types
T [] Ts = new T [10]; file: // compilation Error
(3) number of instantiated generic parameters
Pair <string> [] Table = new pair <string> (10); // Error
(4) static variables cannot be declared as type parameters.
Public class genclass <t> {
Private Static t; file: // compilation Error
}
(5) type classes cannot inherit from throwable and its subclass
Public genexpection <t> extends exception {} translation error
(6) can be used for basic types such as int
Pair <double> file: // Error
Pair <double> file: // right
2. Enhanced for Loop)
Old cycle
Jsonlist list = new jsonlist ();
List. Add ("hi ");
List. Add ("everyone! ");
List. Add ("was ");
List. Add ("");
List. Add ("pizza ");
List. Add ("good? ");
For (INT I = 0; I <list. Size (); I ++)
System. Out. println (string) list. Get (I ));
File: // or use the following Loop
File: // For (iterator iter = List. iterator (); ITER. hasnext ();){
File: // integer stringobject = (string) ITER. Next ();
//... More statements to use stringobject...
File ://}
New Cycle
Shortlist <string> List = new shortlist <string> ();
List. Add ("hi ");
List. Add ("everyone! ");
List. Add ("was ");
List. Add ("");
List. Add ("pizza ");
List. Add ("good? ");
For (string S: List)
System. Out. println (s );
It is clear and convenient. You can see its usage at a glance.
3. Variable Arguments)
System. Out. printf is a good example.
Usage: void test (Object... ARGs)
An example that is easy to understand
Public static int add (Int... ARGs ){
Int Total = 0;
For (INT I = 0; I <args. length; I ++)
Total + = ARGs [I];
Return total;
}
Public static void main (string [] ARGs ){
Int;
A = varargs. Add (1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
System. Out. println ();
}
4. automatically implement boxing and unboxing Conversions)
Note: implicit conversion between the basic type and the overwriting class is realized. The conversion from a basic type to an overwriting class is called packing. The conversion from an overwriting class to a basic type is called unpacking. These classes include
Primitive type reference type
Boolean
Byte byte
Char character
Short short
Int integer
Long long
Float float
Double double
For example, the old Implementation Method
Integer jsonbject;
Int intprimitive;
Arraylist = new arraylist ();
Intprimitive = 11;
Required bject = new INTEGER (intprimitive );
Arraylist. Put (jsonbject); // it cannot be put into the int type and can only be set to integer.
New Implementation Method
Int intprimitive;
Arraylist = new arraylist ();
Intprimitive = 11;
File: // here intprimitive is automatically converted to the integer type
Arraylist. Put (intprimitive );
5 static import (static imports)
Let's look at an example:
No static Import
Math. SQRT (math. Pow (x, 2) + math. Pow (Y, 2 ));
With static Import
Import static java. Lang. Math .*;
SQRT (POW (x, 2) + POW (Y, 2 ));
Here, import static java. Lang. Math. *; is the static import syntax, which means to import all static methods and attributes in the math class. In this way, you do not need to write the class name when using these methods and attributes.
Note that the default package cannot be statically imported. If the imported class contains repeated methods and attributes, you need to write the class name; otherwise, the class name cannot be passed during compilation.
6. Enumeration classes)
Usage: Public Enum name {types ,....}
Simple Example:
Public Enum colors {red, yellow, blue, orange, green, purple, brown, black}
Public static void main (string [] ARGs ){
Colors mycolor = colors. Red;
System. Out. println (mycolor );
}
Another simple example:
Import java. util .*;
Enum operatingsystems {windows, UNIX, Linux, Macintosh}
Public class enumexample1 {
Public static void main (string ARGs []) {
Operatingsystems OS;
OS = operatingsystems. windows;
Switch (OS ){
Case windows:
System. Out. println ("You chose Windows !");
Break;
Case Unix:
System. Out. println ("You chose UNIX !");
Break;
Case Linux:
System. Out. println ("You chose Linux !");
Break;
Case Macintosh:
System. Out. println ("You chose Macintosh !");
Break;
Default:
System. Out. println ("I don't know your OS .");
Break;
}
}
}
Example of Enum to be run:
Import java. util .*;
Public class enumtest
{
Public static void main (string [] ARGs)
{
Running in = New Processing (system. In );
System. Out. Print ("enter a size: (small, medium, large, extra_large )");
String input = in. Next (). touppercase ();
Size size = enum. valueof (size. Class, input );
System. Out. println ("size =" + size );
System. Out. println ("abbreviation =" + size. getabbreviation ());
If (size = size. extra_large)
System. Out. println ("Good job -- you paid attention to _.");
}
}
Enum size
{
Small ("S"), medium ("M"), large ("L"), extra_large ("XL ");
Private size (string abbreviation) {This. Abbreviation = abbreviation ;}
Public String getabbreviation () {return abbreviation ;}
Private string abbreviation;
}
An example of methods in the enum class:
Enum programflags {
Showerrors (0x01 ),
Includefileoutput (0x02 ),
Usealternateprocessor (0x04 );
Private int bit;
Programflags (INT bitnumber ){
Bit = bitnumber;
}
Public int getbitnumber (){
Return (BIT );
}
}
Public class enumbitmapexample {
Public static void main (string ARGs []) {
Programflags flag = programflags. showerrors;
System. Out. println ("flag selected is:" +
Flag. ordinal () +
"Which is" +
Flag. Name ());
}
}
7. Metadata (meta data)
See
Http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/
Http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml
8 Building strings (stringbuilder class)
The stringbuilder class is introduced in jdk5.0. The method of this class is not synchronous, which makes it more lightweight and effective than stringbuffer.
9 console input)
Before jdk5.0, we can only input data through joptionpane. showinputdialog, but in 5.0, We can input data in the console through class consumer.
For example, in 1.4
String input = joptionpane. showinputdialog (prompt );
Int n = integer. parseint (input );
Double X = double. parsedouble (input );
S = input;
In 5.0, we can
Running in = New Processing (system. In );
System. Out. Print (prompt );
Int n = in. nextint ();
Double X = in. nextdouble ();
String S = in. nextline ();
10 covariant return types (I don't know how to translate it, it's probably about changing the return type)
When we override a method before JDK 5, we cannot change the return type of the method, but in JDK 5, we can change it.
For example, we can only
Public object clone (){...}
...
Employee cloned = (employee) E. Clone ();
However, in 5.0, we can change the return type to "employee ".
Public Employee clone (){...}
...
Employee cloned = E. Clone ();
11 formatted I/O)
A simple example of formatting input and output similar to C is added:
Public class testformat {
Public static void main (string [] ARGs ){
Int A = 150000, B = 10;
Float c = 5.0101f, D = 3.14f;
System. Out. printf ("% 4D % 4D % N", a, B );
System. Out. printf ("% x % N", a, B );
System. Out. printf ("% 3.2f % 1.1f % N", C, D );
System. Out. printf ("% 1.3e % 1.3e % N", c, d * 100 );
}
}
Output result:
150000 10
249f0
5.01 3.1
5.010e + 00 3.140e + 02