15.01 Overview and use of object arrays
1 public class Student 2 {3 //member variable 4 private String name; 5 private int age; 6 7 //Construction method 8 Publi C Student () 9 {ten super (); }12 public Student (String name, Int. age) ( 16) this.name = name;17 this.age = age;18 }19 //Member method// getXxx ()/setxxx () Public String GetName (), { name;25}26, public void SetName (string name) , THIS.name = name;30 }31 + public int getage () { return age;35}36 notoginseng public void Setage (int age), this.age = age;40 }41 @Override43 public String toString () { Student [name=] + name + ", age=" + Age + "]"; }47}
1/** 2 stores information about 5 students in an array and iterates through the array to get every student's information. 3 * Student: Student 4 * member variable: Name,age 5 * Construction method: No parameter, with parameter 6 * Member method: GetXxx ()/setxxx () 7 * Analysis: 8 * A: Create student classes. 9 * B: Create a student array (an array of objects). Ten * C: Create 5 Student objects and assign values. One * D: Put the elements of the C-Step into the array. * E: Iterate through the student array. * */14 public class practice + {public static void main (string[] args) 18 {19//Create student Array (object array). Student[] Students = new STUDENT[5];21//for (int x = 0; x < students.length; + +) 22//{2 3//System.out.println (Students[x]), +//}25//System.out.println ("---------------- -----"); 26 27//Create 5 student objects and assign values. Student S1 = new Student ("Xiaoming"), Student s2 = new Student ("Little Red", "n"); Student s3 = new St Udent ("Xiao Qiang"), Student s4 = new Student ("Wang Choi"), Student s5 = new Student ("Zhang San", 35); 33 34 Place the object in the array. Students[0] = s1;36 students[1] = s2;37 Students[2] = s3;38 students[3] = s4;39 students[4] = s5;40 41//Traverse for (int x = 0; x < students.length; x + +)//system.out.println (Students[x]), Student s = students[x];46 Sy Stem.out.println (S.getname () + "---" +s.getage ()); 47}48}49}
15.02 memory plots for object arrays
15.03 The origin of the collection and its difference from the array
The origin of the Collection class: Object-oriented language is the embodiment of things in the form of objects, so in order to facilitate the operation of multiple objects, Java provides a collection of classes.
The differences between arrays and collections are similar:
Arrays can store the same type of basic data or can store objects of the same type, but the length is fixed
A collection can store only objects of different types, and the length is variable
The collection class features: The collection is used only for storing objects, the collection length is mutable, and the collection can store different types of objects.
15.04 the inheritance system diagram of the integrated collection
Collection container because of the internal data structure, there are many specific containers, according to the common content of the continuous upward extraction, formed a set of framework.
Top-level collection interface of the frame
15.05 Overview of the functions of the collection collection
The root interface in the Collection hierarchy. Collection represents a set of objects, also known as Collection elements. Some collection allow duplicate elements, while others do not. Some of the collection are orderly, while others are unordered. The JDK does not provide any direct implementation of this interface: it provides more specific sub-interfaces (such as Set and List) implementations. This interface is often used to pass collection and operate these collection where it is required to be the most universal.
Basic function test of 15.06 collection collection
Member Methods:
1. Boolean Add (E): Ensure that this collection contains the specified element (optional action).
2. Boolean remove (Object o): Removes a single instance of the specified element from this collection, if one exists (optional action).
3. void Clear (): Removes all elements from this collection (optional action).
4. Boolean contains (Object O): Returns True if this collection contains the specified element.
5. Boolean isEmpty (): Returns True if this collection does not contain an element.
6. Int size (): Returns the number of elements in this collection.
Cases:
1//Create Collection Object 2//Collection C = new Collection (); Error because the interface cannot instantiate 3 Collection c = new ArrayList (); 4 C.add ("Hello"); 5 C.add ("World"); 6 C.add ("Java"); 7//C.clear ();//Remove all elements 8//System.out.println ("Remove:" + c.remove ("Hello"));//Remove an element 9//System.out.println ("Remove: "+ c.remove (" java ee ")); 10//Determines whether the set contains the specified element one by one System.out.println (" contains: "+c.contains (" Hello "));//contains: True12 System.out.println ("contains:" +c.contains ("Android"));//contains:false13 //Judging if the set is empty System.out.println ("IsEmpty:" +c.isempty ()),//ISEMPTY:FALSE15//element number System.out.println ("Size:" +c.size ());// size:317 System.out.println ("C:" + C);//c:[hello, World, Java]
Advanced functional testing of the 15.07 collection collection
Member Methods:
1. Boolean AddAll (collection<? extends e> c):
Adds all the elements in the specified collection to this collection (optional action).
2. Boolean removeall (collection<?> C):
Removes all the elements in this collection that are also contained in the specified collection (optional action).
3. Boolean containsall (collection<?> C):
Returns True if this collection contains all the elements in the specified collection.
4. Boolean retainall (collection<?> C):
Leave only those elements in this collection that are also contained in the specified collection (optional action). In other words, remove all elements in this collection that are not contained in the specified collection.
Cases:
C1.addall (C2);//Adds all the elements in the C2 collection to the C1 collection, C1 to C2 (C1.removeall),//deletes all the elements in the C2 collection that are identical to the C1 collection, return Truec1.containsall (C2) As long as there is one,//determine whether the elements in the C1 collection contain all the elements in the C2, all of which are returned Truec1.retainall (C2);//The C1 collection is preserved in the same element as the C2 collection. Remove other elements, return value indicates whether the C1 collection has changed, returns true without changes, returns false
15.08 Aggregate traversal of the set-to-array traversal
Object[] ToArray (): Returns an array that contains all the elements in this collection.
Cases:
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 Collection c = NE W ArrayList (); 7 c.add ("Hello"), 8 C.add ("World"), 9 c.add ("Java"); object[] Objs = C.toarray (); 12 for (int i = 0; i < objs.length; i++) {+/ /down to String type : string s = (string) objs[i];16 System.out.println (s+ ")" +s.length ()); }19}
Operation Result:
Hello:5world:5java:4
15.09 Collection Store custom objects and traverse cases (using arrays)
Example:
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 Collection c = NE W ArrayList (); 7 //Create student object and add to collection 8 c.add (New Student ("Xiao Ming", "Max")), 9 c.add (New Student ("Little Red", +)), and C.add (new Student ("Xiao Qiang"), C.add (New Student ("Wang Choi", 8)), C.add (New Student ("Zhang San"), object[ ] Objs = C.toarray (); ( int i = 0; i < objs.length; i++) (Student ) Student />system.out.println (S.getname () + ":" +s.getage ()); }20 }21}
Operation Result:
Xiao Ming: 23 Little Red: 32 Xiao Qiang: 14 Wang Choi: 8 three: 16
15.1 Traversal iterator traversal of a set
Iterator<e> Iterator (): Returns an iterator that iterates over the elements of this collection.
Cases:
1//Create set 2 Collection c = new ArrayList (); 3//Create element and add to collection 4 C.add ("Hello"); 5 C.add ("World"); 6 C.add ("Java"); 7//Get iterator, actually return the subclass object, polymorphic 8 Iterator it = C.iterator (); 9 while (It.hasnext ()) Ten { System.out.println (It.next ()); 12}
15.11 Collection Store custom objects and traverse cases (using iterators)
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 Collection c = NE W ArrayList (); 7 //Create student object and add to collection 8 c.add (New Student ("Xiaoming", "Max")), 9 c.add (New Student ("Little Red", +)), C.add (New Student ( "Xiao Qiang"), C.add (New Student ("Wang Choi", 8)), C.add (New Student ("Zhang San"), and Iterator it = C.iterator (); it.hasnext () Student s = (Student) it.next () System.out.println (S.getname () + ":" +s.getage ()); }20 }21}
Discussion on the problems of using 15.12 iterators
1. There are two ways to get an element using an iterator:
Mode 1:
Iterator it = C.iterator (); while (It.hasnext ()) { Student s = (Student) it.next (); System.out.println (S.getname () + ":" +s.getage ());
Mode 2:
for (Iterator it = C.iterator (); It.hasnext ();) { Student s = (Student) it.next (); System.out.println (S.getname () + ":" +s.getage ());
Benefits of using Mode 2: It becomes garbage at the end of the for loop and is more efficient
2. Do not use the It.next () method multiple times
Cases:
Iterator it = C.iterator (); while (It.hasnext ()) { System.out.println (((Student) It.next ()). GetName ()); System.out.println (((Student) It.next ()). Getage ());
The above code indicates the 1th student's name, The age of the 2nd student, and so on, if the element in the collection is an odd number, the nosuchelementexception error is reported
15.13 schematic diagram of the use steps of the integrated collection
Steps to use the collection:
1. Create a Collection Object
2. Creating an Element Object
3. Adding elements to the collection
4. Iterating through the collection
4.1 Getting an Iterator object from a collection object
4.2 Determine if there are elements through the Hasnext () method of the Iterator object
4.3 Gets the element and moves to the next position via the next () method of the Iterator object
The principle and source code analysis of 15.14 iterators
Principle:
Assuming an iterator defines a class, you can create an object of that class, call the method of the class to implement the traversal of the collection, but there are many collection classes in Java, and the data structures of the collection classes are different, so the way you store them and the way you traverse them should be different, And then they should traverse in a different way. Finally, there is no iterator class defined
Regardless of which collection should have the operation of acquiring elements, and it is best to re-assist and judge the function, that is, the judgment function and the acquisition function should be a collection traversal, and each kind of collection is not the same way, so the two functions to extract, do not provide a concrete implementation, this is the interface, and the real implementation class is embodied in the inner class in the specific subclass.
Source:
Public interface Iterator { boolean hasnext (); Object next (); }public interface Iterable { Iterator Iterator ();} Public interface Collection extends iterable { Iterator Iterator ();} Public interface List extends Collection { Iterator Iterator ();} public class ArrayList implements List {public Iterator Iterator () { return new Itr (); } Inner class Private class Itr implements Iterator {public boolean hasnext () {} public Object next () {}< C14/>}}collection C = new ArrayList (); C.add ("Hello"); C.add ("World"); C.add ("Java"); Iterator it = C.iterator () ; New Itr (); while (It.hasnext ()) { string s = (string) it.next (); System.out.println (s);}
15.15 Collection store strings and traverse
1 Import java.util.ArrayList; 2 Import java.util.Collection; 3 Import Java.util.Iterator; 4 5 public class practice 6 {7 8 public static void Main (string[] args) 9 {Ten //Create a collection of Co Llection C = new ArrayList (); //Add string c.add ("Hello"), c.add ("Hello"), C.add ("World"); 18 C.add ("Java"); c.add ("Wang Choi"); Gets an iterator object from a collection object. Iterator it = C.iterator (); (It.hasnext ()) : It.next (String), System.out.println (s); }30 31 }32 33}
15.16 Collection store student objects and traverse
1 Import java.util.ArrayList; 2 Import java.util.Collection; 3 Import Java.util.Iterator; 4 5 public class practice 6 {7 public static void Main (string[] args) 8 {9 //Create collection Collection c = new ArrayList (); create student object and add to collection C.add (New Student ("Xiao Ming"); C.add (New Student ("Little Red", 32)); 14 C.add (New Student ("Xiao Qiang"), C.add (New Student ("Mong Choi", 8)), C.add (New Student ("Zhang San" ); Iterator it = C.iterator (); while (It.hasnext ()) { Student s = (Student) it.next (); 22 System.out.println (S.getname () + ":" +s.getage ()); }25}
15.17 List stores strings and iterates through
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 List List = new A Rraylist (); 7 list.add ("Hello"), 8 List.add ("World"), 9 list.add ("Java"), Iterator it = list.iterator ( ), and (It.hasnext ()) (): ( string), It.next (), System.out.println (s) ; }17 }18}
Features of the 15.18 list collection
List Interface Overview: ordered (consistent access order) collection (also known as sequence). Users of this interface can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list.
Features: Unlike set, a list usually allows repeating elements.
15.19 List stores student objects and iterates through
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 List List = new A Rraylist (); 7 //Create student object and add to collection 8 list.add (New Student ("Xiao Ming", "Max")), 9 list.add (New Student ("Little Red"), and List.add ( New Student ("Xiao Qiang"), List.add (New Student ("Wang Choi", 8)), List.add (New Student ("Zhang San"), 14 Iterator it = List.iterator (); 18 (It.hasnext ()) + { Student s = (Student) it.next System.out.println (S.getname () + ":" +s.getage ()); }21}
Overview and testing of unique features of the 15.20 list collection
1. void Add (int index,e Element):
Inserts the specified element (optional action) at the specified position in the list.
2. E Remove (int index):
Removes the element from the specified position in the list (optional action).
3. E get (int index):
Returns the element at the specified position in the list.
4. E Set (int index, e Element):
Replaces the element in the specified position in the list with the specified element (optional action).
Cases:
List.add (2, "Java ee");//Insert Java EE at 2, change the set length
List.get (2)//Returns the element at 2 position in the collection without changing the set length
List.remove (1)//Remove elements from 1 positions in the collection, return deleted elements, change set length
List.set (2, "Java EE")//replace the elements in the collection with the Java EE on the 2 position, return the replaced element without changing the set length
15.21 the unique traversal function of the list collection
1 for (int i = 0; i < list.size (); i++) 2 3 {4 5 String s = (String) list.get (i); 6 7 System.out.println (s); 8 9 }
15.22 List stores custom objects and iterates through them (using the list-specific feature traversal)
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 List List = new A Rraylist (); 7 //Create student object and add to collection 8 list.add (New Student ("Xiao Ming", "Max")), 9 list.add (New Student ("Little Red"), and List.add ( New Student ("Xiao Qiang"), List.add (New Student ("Wang Choi", 8)), List.add (New Student ("Zhang San"), 14 for (int i = 0; i < list.size (); i++) { Student s = (Student) list.get (i); System.out.println (S.getname () + ":" +s.getage ());}19}20 }
Unique features of 15.23 Listiterator
Listiterator<e> Listiterator ():
Returns the list iterator for this list element, in the appropriate order.
Note: Listiterator can implement reverse traversal, but must be traversed first to reverse traverse
Cases:
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 List List = new A Rraylist (); 7 8 list.add ("Hello"), 9 List.add ("World"), list.add ("Java"), one //list iterator Listiterator lit = List.listiterator (); //forward traversal of the (Lit.hasnext ()). {. string s = (string ) Lit.next (), System.out.println (s), }19 System.out.println ("-----"), and/ or reverse traverse while (Lit.hasprevious ()) all { //Gets the previous element (string s = (string) lit.previous (); System.out.println (s); }27 }29}
Operation Result:
Hello
World
Java
-----
Java
World
Hello
15.24 Causes and solutions of concurrency modification exceptions
Cases:
1 public class Practice 2 {3 public static void Main (string[] args) 4 {5 //Create collection 6 List List = New ArrayList (); 7 8 list.add ("Hello"), 9 List.add ("World"), list.add ("Java"), Iterator it = List.iterator (), while (It.hasnext ()) (a) (String ), It.next (), and if (S.equals (" World ") list.add (" Java ee "); }18 System.out.println (list); }20}
The above code will run the error, Concurrentmodificationexception exception occurred
The cause of the error: The iterator is dependent on the collection, and the method of using the collection in the iterative process adds an element iterator that is not known, so error, concurrency modification exception
Solution: 1. Use iterators to modify elements when iterating over elements (listiterator list iterators), adding elements behind the elements of an iteration
2. Iterate through the elements with the collection, modify the elements with the set (for loop), add the elements in the last
15.25 Stack and queue of data structures
Data structure: How it is organized
15.26 arrays and linked lists of data structures
Arrays: Containers that store multiple elements of the same type
Linked list: Data composed of multiple nodes (data and nodes) connected by a chain.
Features of the three subcategories of the 15.27 list
ArrayList: The underlying data structure is an array, query fast, adding and deleting slow, is not synchronized, thread insecure, high efficiency
Vector: The underlying data structure is an array, query fast, delete and subtract slowly, is synchronous, thread-safe, inefficient
LinkedList: The underlying data structure is linked list, query slow, and delete fast, is not synchronized, thread unsafe, high efficiency
Javase Learning Summary 15th Day _ Collection Frame 1