The ArrayList of the Core Java thing.
High-rise ground, Java Foundation to pick up. Today, I looked at the core Java from the basic point to find a little bit to share.
First of all, the professional-level Lucky Star actor---employee Class (PS: I am focused on Lucky Star 30), there will be several appearances, so first here to introduce:
1 class employee{2 Private String name; 3 Private Double salary; 4 Private int ID; 5 6 // here is the set, get method 7 }
ArrayList
First of all, please ArrayList debut and introduce yourself: I am a generic class (generic class) that takes a type parameter (types parameter). To specify the element object type that the array list holds, I use a pair of angle brackets to enclose the class name, such as,arraylist<employee> (Employee: It's my turn to Lucky Star) ... Balabala (omit 10086 words here). Well, here's how to use him.
1. Disclaimer:
1 New Arraylist<employee> ();
God, there are employee on both sides, which is too much trouble. If you have trouble, please use Java7, in Java7, you can omit the right type parameter as follows:
1 New Arraylist<> ();
This is also referred to as the "diamond" syntax, because an empty angle bracket is like a diamond. You can use the diamond syntax in conjunction with the new operator. The compiler checks what the new value is, if it is assigned to a variable, or is passed to a method, or is returned from a method, the compiler examines the generic type of the variable, parameter, or method, and then places the type in <>, in this case, the Lucky Star actor is the employee, Therefore, the generic type is employee.
2. Add :
1 staff.add (new Employee ("Harry Hacker" ...)); 2 staff.add (new Employee ("Tony Michel" ...));
3. Get the actual size of the array:
1 staff.size ();
4. Accessing array list elements :
4.1. Replace:
1 staff.set (I,harry);
Note: This method is somewhat equivalent to A[i]=harry. However, this method can only replace the element content that already exists in the array.
4.2. Get :
1 Employee e = Staff.get (i);
Equivalent to: Employee e = a[i];
5. Insert the new element :
1 New Arraylist<>(); 2 while (...) 3 {4 x= ...; 5 List.add (x); 6 }
View Code
you can then use the ToArray method to copy the array into an array.
1 New x[list.size ()]; 2 List.toarray (a);
In addition, you can include elements in the middle of the array list:
1 int n = staff.size ()/2; 2 staff.add (n, e);
6. Delete the element :
1 Employee e = Staff.remove (n);
7. Iterate through the array :
General Method :
1 for (int i = 0; I<staff.size (); i++) 2 {3 Employee e = staff.get (i); 4 // Do somne thing with e 5 }
a method of forcing a little higher (for Each loop):
1 for (Empolyee e:staff) 2 {3 // Do something withe e 4 }
PS: This blog welcome forwarding, but please specify the blog address and author ~
Blog Address: http://www.cnblogs.com/voidy/
<. ))) ≦
The ArrayList of the Core Java thing.