Java -- Collection collection, iterator, generics

Keywords: Programming Java JDK

aggregate

——Collection is a container provided by java, which can be used to store multiple data.

The difference between set and array

  1. The length of the array is fixed. The length of the set is variable.
  2. The array stores elements of the same type, which can store basic data type values.
  3. Collections store objects. And the types of objects can be inconsistent. In development, when there are many objects, the collection is used for storage.

Interface inheritance and Implementation

Collection classes are stored in the Java.util package. There are three main types: set (set), list (list contains Queue), and map (map).

1. **Collection: * * Collection is the most basic interface for Collection List, Set and Queue.

2. **Iterator: * iterator, which can traverse the data in the collection

3. **Map: * * is the basic interface of mapping table

Collection

The root interface of a single column collection class is used to store a series of elements that conform to certain rules. It has two important sub interfaces, namely * * java.util.List * * and * * java.util.Set * *.

The difference between List and Set

  1. `List 'is characterized by orderly elements and repeatable elements. `Set 'is characterized by element disorder and non repetition.
  2. `The main implementation classes of the List interface are 'java.util.ArrayList' and 'java.util.LinkedList',
  3. `The main implementation classes of the Set interface are 'java.util.HashSet' and 'java.util.TreeSet'.

Common methods of Collection

//Adds the given object to the current collection.
public boolean add(E e)

//Empty all elements in the collection.
public void clear()

//Delete the given object in the current collection.
public boolean remove(E e)

//Determines whether the current collection contains the given object.
public boolean contains(E e)

//Determines whether the current set is empty.
public boolean isEmpty()

//Returns the number of elements in the collection.
public int size()

//Store the elements in the collection into an array.
public Object[] toArray()

Iterator iterator

In program development, it is often necessary to traverse all elements in a Collection. To meet this demand, JDK provides an interface 'java.util.Iterator'. `The iterator interface is also a member of the Java Collection, but it is different from the 'Collection' and 'Map' interfaces. The 'Collection' interface and the 'Map' interface are mainly used to store elements, while the 'iterator' interface is mainly used to iterate over the elements in the 'Collection'. Therefore, the 'iterator' object is also called an iterator.

iteration

This is the general way to get Collection collection elements. Before fetching the elements, you should first judge whether there are elements in the Collection. If there are any, you should take out the elements, continue to judge, and if there are any, you can take them out again. Always take all the elements out of the Collection. The term for this extraction method is iteration.

The common methods of Iterator interface are as follows:

//Gets the iterator corresponding to the collection, which is used to traverse the elements in the collection.
public Iterator iterator()

//Returns the next element of the iteration.
public E next()

//Returns true if there are still elements to iterate over.
public boolean hasNext()


/*
 *example
 */
public class IteratorDemo {
  	public static void main(String[] args) {
        // Creating objects using polymorphism
        Collection<String> coll = new ArrayList<String>();

        // Add element to collection
        coll.add("String of stars");
        coll.add("love remains ");
        coll.add("dog");
        //ergodic
        //Using iterators to traverse each collection object has its own iterator
        Iterator<String> it = coll.iterator();
        //  Generics are data types that iterate out elements
        while(it.hasNext()){ //Determine if there are iteration elements
            String s = it.next();//Get iterated elements
            System.out.println(s);
        }
  	}
}

Principle of iterator

When Iterator iterator object traverses the collection, it uses pointer to trace the elements in the collection. Before calling the next method of Iterator, the index of Iterator is located before the first element and does not point to any element. When the next method of Iterator is called for the first time, the index of Iterator will move backward one bit, point to the first element and return the element. When the next method is called again, the index of Iterator will point to the second element and return the element, and so on By analogy, until the hasNext method returns false, indicating that the end of the collection is reached and the traversal of the element is terminated.

Enhance for loop

Enhanced for loop (also known as for each loop) is an advanced for loop after JDK 1.5, which is specially used to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so in the process of traversal, you cannot add or delete elements in the collection.

For (data type variable of element: Collection collector array){ 
  	//Write operation code
}

generic paradigm

Although Collection can store various objects, in fact, Collection usually only stores objects of the same type. For example, they are all storage string objects. So after JDK5, generic syntax has been added.

Generics: it is an unknown data type. When we don't know what data type to use, we can use generics

Generics can also be seen as a variable to receive data types

Benefits of using generics

Transferring the runtime ClassCastException to compile time becomes Compile failure. It avoids the trouble of type forced conversion.

The definition and use of generics

Defining and using classes with generics

//Definition format: modifier class name < variable representing generic > {}
//eg: 
class ArrayList<E>{ 
    public boolean add(E e){ }

    public E get(int index){ }
   	....
}

//Determine generics when creating objects
//eg: 
ArrayList<String> list = new ArrayList<String>()
//At this point, the value of variable E is String type, so our type can be understood as:
class ArrayList<String>{ 
     public boolean add(String e){ }

     public String get(int index){  }
     ...
}

Methods with generics

//Modifier < variable representing generic > return value type method name (parameter) {}

//eg: definition
public class MyGenericMethod {	  
    public <MVP> void show(MVP mvp) {
    	System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {	
    	return mvp;
    }
}

//Use
public class GenericMethodDemo {
    public static void main(String[] args) {
        // create object
        MyGenericMethod mm = new MyGenericMethod();
        // Tips for demonstration
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}

Interfaces with generics

//Modifier interface interface name < variable representing generic > {}

/*
 *eg:Determine the type of generics when defining classes
 */
//definition
public interface MyGenericInterface<E>{
	public abstract void add(E e);
	
	public abstract E getE();  
}

//Use
public class MyImp1 implements MyGenericInterface<String> {
	@Override
    public void add(String e) {
        // Omit
    }

	@Override
	public String getE() {
		return null;
	}
    //At this point, the value of generic E is of type String.
}


/*
 *eg:The type of the generic is never determined until the object is created
 */
//definition
public class MyImp2<E> implements MyGenericInterface<E> {
	@Override
	public void add(E e) {
       	 // Omit
	}

	@Override
	public E getE() {
		return null;
	}
}

//Use
public class GenericInterface {
    public static void main(String[] args) {
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa");
    }
}

Posted by bakaneko on Sun, 22 Dec 2019 02:12:09 -0800