Java programming-sun Xin Java is no difficulty lesson6 array-related operations, several special classes, design patterns
Highlights of this section:
1. array-related operations
2. encapsulation class
3. runtime and Process
4. Class class
5. Design Mode
Details:
1. array-related operations
(1)Copy basic array elements
The test code is as follows:
//************************************** **************************************** *
Int [] num1 = new int [] {1, 2, 3 };
Int [] num2 = new int [10];
// System. arraycopy (num1, 0, num2, 0, num1.length); // OK
System. arraycopy (num1, 0, num2, 7, num1.length); // OK if 8 error parameter is related
System. arraycopy (num1, 0, num2, 8, 2); // OK
For (INT I = 0; I <num2.length; I ++)
System. Out. println (num2 [I]);
(2)Copying object arrays
The test code is as follows:
//************************************** **************************************** *
Point pts1 [] = new point [] {New Point (), new point (), new point )};
Point pts2 [] = new point [3];
System. arraycopy (pts1, 0, pts2, 0, pts1.length); // copies the same memory as the object references.
For (INT I = 0; I <pts2.length; I ++)
System. Out. println ("x =" + pts2 [I]. x + "," + "Y =" + pts2 [I]. y );
Pts2 [1]. x = 5;
Pts2 [1]. Y = 5;
System. out. println ("x =" + pts1 [1]. X + "," + "Y =" + pts1 [1]. y); // pts1 data is modified to 5, 5
(3)Array sorting and element searching
Note: When the custom class does not implement the comparable interface, it cannot be sorted. The error message is as follows:
//************************************** **************************************** *
Exception in thread "Main" Java. Lang. classcastexception: student cannot be cast
To java. Lang. Comparable
At java. util. comparabletimsort. countrunandmakeascending (unknown source)
At java. util. comparabletimsort. Sort (unknown source)
At java. util. comparabletimsort. Sort (unknown source)
The array Sorting Test code is as follows:
//************************************** **************************************** *
// Sorting and searching of array elements
Int [] num = new int [] {3, 1, 2 };
Arrays. Sort (Num); // static method
For (INT I = 0; I <num. length; I ++)
System. Out. println (Num [I]);
Int Index = arrays. binarysearch (Num, 2); // search for the sorted Array
If (-1! = Index)
{
System. Out. println ("Data found! ");
System. Out. println ("Index =" + index + ", Data =" + num [Index]);
}
//************************************** **************************************** *
// Running result
1
2
3
Data found!
Index = 1, data = 2
//************************************** **************************************** *
Test code for sorting and searching object arrays is as follows:
//************************************** **************************************** *
Class student implements comparable
{
String name;
Int num;
Student (string name, int num)
{
This. Name = Name;
This. num = num;
}
Public String tostring ()
{
Return "num =" + num + ", name =" + name;
}
Public int compareto (Object O)
{
Student Stu = (student) O;
Int ret = num> Stu. Num? 1 :( num = Stu. Num? 0:-1 );
// Sort names with the same serial number
If (0 = RET)
{
Ret = Name. compareto (STU. Name );
}
Return ret;
}
}
Class arraytest
{
Public static void main (string [] ARGs)
{
Student [] students = new student [] {New Student ("zhangsan", 1), new student ("Lisi", 2), new student
("Zhaoer", 3), new student ("wangwu", 3 )};
Arrays. Sort (students );
For (INT I = 0; I <students. length; I ++)
System. Out. println (students [I]);
Int Index = arrays. binarysearch (students, new student ("Lisi", 2); // search for the sorted Array
If (-1! = Index)
{
System. Out. println (students [Index]);
}
}
//************************************** **************************************** *
// Running result
Num = 1, name = zhangsan
Num = 2, name = Lisi
Num = 3, name = wangwu
Num = 3, name = zhaoer
Num = 2, name = Lisi
2. encapsulation class
The corresponding reference type-encapsulation class defined for the eight basic data types.
Shows the encapsulation class:
The encapsulation test code is as follows:
//************************************** **************************************** *
Class Test
{
Public static void main (string [] ARGs)
{
Int I = 3;
Integer in = new INTEGER (I); // the contents of the encapsulated class cannot be modified.
Int J = in. intvalue ();
System. Out. println ("J =" + J );
String STR = in. tostring ();
System. Out. println ("str =" + Str );
String str2 = "123 ";
System. Out. println (integer. valueof (str2 ));
System. Out. println (integer. parseint (str2 ));
}
}
3. runtime and Process
(1)Features of the runtime class:
A. Each Java program has a single runtime class instance.
B. Get the runtime class instance through runtime. getruntime.
C. The runtime class is an example of the singleton mode.
(2)Enable a new process to execute other tasks using the runtime method. The new process is controlled by the returned process object.
The test code is as follows:
//************************************** **************************************** *
Import java. Io .*;
Class runtimetest
{
Public static void main (string [] ARGs)
{
Runtime RT = runtime. getruntime (); // only one unique instance can be obtained.
System. Out. println (RT. freememory ());
System. Out. println (RT. totalmemory ());
Try
{
// Rt.exe C ("Notepad"); // open notepad
Rt.exe C ("javac arraytest. Java"); // compile the source file
Process ps=rt.exe C ("Java arraytest"); // run the class file and save the process object
// Display the result to the current output window
Inputstream is = ps. getinputstream ();
Int data;
While (Data = is. Read ())! =-1)
{
System. Out. Print (char) data );
}
}
Catch (exception E)
{
System. Out. println (E. tostring ());
}
}
}
//************************************** **************************************** *
// Running result
15725992
16252928
Num = 1, name = zhangsan
Num = 2, name = Lisi
Num = 3, name = wangwu
Num = 3, name = zhaoer
Num = 2, name = Lisi
4. Class class
(1)What is a class?
In Java, each class has a corresponding class object. That is to say, after compiling a class,
In the generated. Class file, a class object is generated to indicate the type information of the class.
(2)Three methods for getting a class instance
A. Call the getclass () method to obtain the class instance of the object;
B. Use the static method forname () of the class to obtain a class instance with the class name;
C. Use the. Class method to obtain the class instance. For the encapsulation class of the basic data type,
You can also use. type to obtain the corresponding class instance of the basic data type.
Obtain the test code of the class:
//************************************** **************************************** *
Class classtest
{
Public static void main (string [] ARGs)
{
/*
Point Pt = new point (3, 4 );
Class Cl = pt. getclass ();
System. Out. println (Cl. getname ());
Try
{
Class Cl2 = Class. forname ("point ");
System. Out. println (cl2.getname ());
}
Catch (classnotfoundexception E)
{
System. Out. println (E. tostring ());
}
Class l3 = point. Class;
System. Out. println (cl3.getname ());
Class cl4 = int. Class;
System. Out. println (cl4.getname ());
Class cl5 = integer. type;
System. Out. println (cl5.getname ());
Class cl6 = integer. Class;
System. Out. println (cl6.getname ());
}
//************************************** **************************************** *
// Running result
Point
Point
Point
Int
Int
Java. Lang. Integer
(3)Class loading time
During running, if we want to generate a class object, the Java Virtual Machine (JVM) checks whether the class object of this type has been loaded. If the file is not loaded, JVM will find the. Class file based on the class name and load it. Once a class object of a certain type has been loaded into the memory, it can be used to generate all objects of this type.
The execution time of static code is used to reflect the class loading time. The test code is as follows:
//************************************** **************************************** *
Class Point
{
Int X, Y;
Point (int x, int y)
{
This. x = X;
This. Y = y;
}
// Static code segment
Static
{
System. Out. println ("loading point! ");
}
Void output ()
{
System. Out. println ("x =" + x + "Y =" + y );
}
}
Class line
{
Static
{
System. Out. println ("loading line! ");
}
}
Class classtest
{
Public static void main (string [] ARGs)
{
System. Out. println ("before new point! ");
New Point (3, 4 );
System. Out. println ("after new point! ");
Try
{
Class. forname ("line ");
}
Catch (classnotfoundexception E)
{
System. Out. println (E. tostring ());
}
}
//************************************** **************************************** *
// Running result
Before new point!
Loading point!
After new point!
Loading Line!
(4)Dynamic instance creation using the reflection API
The test code is as follows:
//************************************** **************************************** *
// Dynamically create an object and obtain its constructor and Method
If (ARGs. length! = 1)
Return;
Try
{
Class Cl = Class. forname (ARGs [0]);
Constructor [] cs = Cl. getdeclaredconstructors ();
For (INT I = 0; I <CS. length; I ++)
System. Out. println (CS [I]);
Method [] M = Cl. getdeclaredmethods ();
For (INT I = 0; I <M. length; I ++)
System. Out. println (M [I]);
}
Catch (exception E)
{
E. printstacktrace ();
}
//************************************** **************************************** *
// Running result
F: \ Java \ javalesson \ lesson6> JAVA classtest point
Loading point!
Point (INT, INT)
Void point. Output ()
(5)How to judge the constructor when creating an instance dynamically
The newinstance method of the class calls the default constructor of the class. If the default constructor is missing, an error occurs. The error message is as follows:
//************************************** **************************************** *
F: \ Java \ javalesson \ lesson6> JAVA classtest point
Loading Line!
Loading point!
Java. Lang. instantiationexception: Point
At java. Lang. Class. newinstance0 (unknown source)
At java. Lang. Class. newinstance (unknown source)
At classtest. Main (classtest. Java: 65)
At java. util. arrays. Sort (unknown source)
At arraytest. Main (arraytest. Java: 41)
Solution: first obtain the constructor method and corresponding parameter information, and then dynamically create an instance.
The test code is as follows:
//************************************** **************************************** *
If (ARGs. length! = 1)
Return;
Try
{
Class Cl = Class. forname (ARGs [0]);
Constructor [] cs = Cl. getdeclaredconstructors ();
// Only one constructor is known
Class [] Params = cs [0]. getparametertypes ();
Object [] paramvalues = new object [Params. Length];
For (INT I = 0; I <Params. length; I ++)
{
If (Params [I]. isprimitive ())
{
Paramvalues [I] = new INTEGER (I + 3 );
}
}
Object Ob = cs [0]. newinstance (paramvalues );
// Only one method is known and the method has no parameters.
Method [] M = Cl. getdeclaredmethods ();
M [0]. Invoke (OB, null );
}
Catch (exception E)
{
E. printstacktrace ();
}
//************************************** **************************************** *
// Running result
F: \ Java \ javalesson \ lesson6> JAVA classtest point
Loading point!
X = 3y = 4
5. Design Mode
What is the design model:
During our program design, we gradually formed some typical problems and solutions. This is the software model.
Each pattern describes a problem that often occurs in our program design and the solution to the problem. Why do we need a design pattern:
When we encounter the problem described in the pattern, we can use the corresponding solution to solve the problem. This is the design pattern.
We need to learn more about the design model.