javaSE___ Collection system 02 -- collection, iterator

1, Basic function test of Collection

The first method: Boolean add (E) add elements. The test is as follows:

public static void main(String[] args) {
        Collection c = new ArrayList();		//A parent class reference points to a child class object
        boolean b1 = c.add("abc");
        boolean b2 = c.add(true);			//Auto boxing new Boolean(true);
        boolean b3 = c.add(100);
        boolean b5 = c.add("abc");

        System.out.println(b1);             //true
        System.out.println(b2);             //true
        System.out.println(b3);             //true
        System.out.println(b5);             //true

        System.out.println(c);   //[abc, true, 100, abc]
    }

   1. We found that no matter what we add, its output is true, because the add method of the subclass ArrayList returns true no matter what is added, which only returns true in the List set. If you store duplicate values in the set set, it returns false to you.
   2. The last output statement adds the output in order. Similarly, the parent class of the parent class of ArrayList rewrites the toString method, so it can output all the values. If the toString method is not rewritten, the output should be / / the class name on the left, the @ symbol in the middle, and a hashcode16 input value on the right, such as com chenjiangang. domain. User@7185d3cc

The second method: boolean remove(Object o) deletes elements. The test is as follows:

public static void main(String[] args) {
		Collection c = new ArrayList();		
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		c.remove("b");				//Delete the specified element
		System.out.println(c);		//[a, c, d]
	}

The third method: void clear() clears the collection. The test is as follows:

public static void main(String[] args) {
		Collection c = new ArrayList();		
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		c.clear();					//Empty collection
		System.out.println(c);		//[]
	}

The fourth method: boolean contains(Object o) to judge whether it contains. The test is as follows:

public static void main(String[] args) {
		Collection c = new ArrayList();		
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		System.out.println(c.contains("b"));	//Determine whether the output is true
	}

The fifth method: boolean isEmpty() determines whether it is empty. The test is as follows:

public static void main(String[] args) {
		Collection c = new ArrayList();		
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		System.out.println(c.isEmpty());    //Judge whether it is empty and the output is false
	}

The sixth method: int size() gets the number of elements. The test is as follows:

public static void main(String[] args) {
		Collection c = new ArrayList();		
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		System.out.println(c.size()); 	    //Get the number of elements, and the output is 4
	}

2, The traversal of the Collection is converted to array traversal.

We don't need iterators here. We don't need so much trouble with iterations.

1. In the first example, a string is added.

public static void main(String[] args) {
		
		Collection c = new ArrayList();
		c.add("a");
		c.add("b");
		c.add("c");
		c.add("d");
		
		Object[] arr = c.toArray();						//Convert a collection to an array
		for(int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);			//a,b,c,d
		}
	}

2. The second example adds a custom object.

public static void main(String[] args) {
		Collection c = new ArrayList();
		c.add(new Student("Zhang San", 23));			
		c.add(new Student("Li Si", 24));
		c.add(new Student("Wang Wu", 25));
		c.add(new Student("Zhao Liu", 26));
		
		Object[] arr = c.toArray();				//Convert a collection to an array
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);			//Output: Zhang San Li Si Wang Wu Zhao Liu
		}
	}

3. On the basis of the second example, let's make an extension. We don't print arr directly, and then print after obtaining it.

Collection c = new ArrayList();
		c.add(new Student("Zhang San", 23));				//Object obj = new Student("Zhang San", 23);
		c.add(new Student("Li Si", 24));
		c.add(new Student("Wang Wu", 25));
		c.add(new Student("Zhao Liu", 26));
		
		Object[] arr = c.toArray();					//Convert a collection to an array
		for (int i = 0; i < arr.length; i++) {
			//System.out.println(arr[i]);
			Student s = (Student)arr[i];			//Downward transformation
			System.out.println(s.getName() + "..." + s.getAge());   //Output: Zhang San Li Si Wang Wu Zhao Liu
		}

3, Function test with All for Collection

1. The first method, boolean addAll(Collection c), transfers one set to another. The test is as follows:

public static void demo1() {
		Collection c1 = new ArrayList();
		c1.add("a");
		c1.add("b");
		c1.add("c");
		c1.add("d");
		
		Collection c2 = new ArrayList();			//alt + shift + r select one to rename all
		c2.add("a");
		c2.add("b");
		c2.add("c");
		c2.add("d");
		
		//c1.addAll(c2); 							// Add each element in C2 to C1
		c1.add(c2);									//Add c2 as an object to c1
		System.out.println(c1);			//Output [a, b, c, d, [a, b, c, d]]
	}

2. The second method, boolean removeAll(Collection c), deletes the intersection. The test is as follows:

public static void main(String[] args) {

        Collection c1 = new ArrayList();
        c1.add("a");
        c1.add("b");
        c1.add("c");
        c1.add("d");

        Collection c2 = new ArrayList();
        c2.add("a");
        c2.add("b");
        c2.add("z");

        boolean b = c1.removeAll(c2);					//The intersection is deleted
        System.out.println(b);          //true
        System.out.println(c1);         //The output is: [c, d]
    }

3. The third method, boolean containsAll(Collection c), judges whether a collection contains elements in another collection. The test is as follows:

public static void main(String[] args) {
        Collection c1 = new ArrayList();
        c1.add("a");
        c1.add("b");
        c1.add("c");
        c1.add("d");

        Collection c2 = new ArrayList();
        c2.add("a");
        c2.add("b");
        c2.add("z");

        boolean b = c1.containsAll(c2);				//Determine whether the incoming collection contains
        System.out.println(b);         //false
    }

4. The fourth method, Boolean retain all (collection C), preserves the intersection. The test is as follows:

public static void main(String[] args) {

        Collection c1 = new ArrayList();
        c1.add("a");
        c1.add("b");
        c1.add("c");
        c1.add("d");

        Collection c2 = new ArrayList();
        c2.add("a");
        c2.add("b");
        c2.add("c");
        c2.add("d");
        c2.add("e");
        c2.add("f");

        //Take the intersection. If the called set changes, it returns true. If the called set does not change, it returns false
        boolean b = c1.retainAll(c2);					//intersect 
        System.out.println(b);              //false
        System.out.println(c1);             //[a, b, c, d]
    }

4, Iterator traversal of a collection

1. For a simple example of iteration, get an element. hasNext (): judge whether there is an element in the set. next(): get the first element. For each bit, move the pointer down one bit

public static void main(String[] args) {
        
        Collection c = new ArrayList();
        c.add("a");
        c.add("b");
        c.add("c");
        c.add("d");

        //Iterates (traverses) the elements in the collection
        Iterator it = c.iterator();			//Get iterator
		boolean b1 = it.hasNext();			//Judge whether there are elements in the collection, and return true if there are
		Object obj1 = it.next();            //Get the first element, and move the pointer down one bit for each bit
		System.out.println(b1);             //true
		System.out.println(obj1);           //a

		boolean b2 = it.hasNext();			//Judge whether there are elements in the collection, and return true if there are
		Object obj2 = it.next();
		System.out.println(b2);             //true
		System.out.println(obj2);           //b
    }

2. The while iteration loops through the output set

public static void main(String[] args) {

        Collection c = new ArrayList();
        c.add("a");
        c.add("b");
        c.add("c");
        c.add("d");

        //Iterates (traverses) the elements in the collection
        Iterator it = c.iterator();			//Get iterator
        while(it.hasNext()) {
            System.out.println(it.next());		//There are 4 lines in total, and 4 elements are output
        }
    }

3. Iterate over a custom class and use the toString method

public static void main(String[] args) {

        Collection c = new ArrayList();
        c.add(new Student("Zhang San", 23));				//Object obj = new Student("Zhang San", 23);
        c.add(new Student("Li Si", 24));
        c.add(new Student("Wang Wu", 25));
        c.add(new Student("Zhao Liu", 26));

        //Get iterator
        Iterator it = c.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());		//Output the object added above
        }
    }

4. Iterate over a custom class and use the get method

 public static void main(String[] args) {

        Collection c = new ArrayList();
        c.add(new Student("Zhang San", 23));				//Object obj = new Student("Zhang San", 23);
        c.add(new Student("Li Si", 24));
        c.add(new Student("Wang Wu", 25));
        c.add(new Student("Zhao Liu", 26));

        //Get iterator
        Iterator it = c.iterator();
        while(it.hasNext()) {
            Student s = (Student)it.next();			//Downward transformation
            System.out.println(s.getName() + "..." + s.getAge());	//Output the object added above
        }
    }

5, (iterator principle and source code analysis) (understand)

Iterator principle:
   iterator principle: an iterator traverses a collection, and the internal storage structure of each collection is different, so the storage and retrieval of each collection are different. Therefore, it is necessary to define hasNext() and next() methods in each class. This is possible, but it will make the whole collection system too cumbersome. The iterator extracts the interface of such methods upward, Then define your own iteration method inside each class. This has two advantages. First, it stipulates that the traversal method of the whole collection system is hasNext() and next() methods. Second, the code has an underlying internal implementation. Users can use it regardless of how to implement it.

Iterator source code analysis:
   * 1, find the ArrayList class in eclipse by ctrl + shift + t
   * 2,ctrl+o find iterator() method
   * 3. Check that the return value type is new Itr(), indicating that Itr implements the Iterator interface
   * 4, find the internal class Itr and find that it rewrites all the abstract methods in Iterator

----

It's not easy to create. If you feel good, please praise it. Thank you~~

Keywords: Java JavaSE set

Added by moomsdad on Tue, 08 Feb 2022 17:54:24 +0200