Java learning collection ArrayList, collection, Iterator iterator, enhanced for loop, generic

ArrayList collection

ArrayList is a data structure that implements dynamic arrays. Unlike arrays, it does not need to specify a size when it is created, and can automatically increase the capacity according to the saved content. You can use ArrayList when you don't know how much data you need to save.

Exercise: Adding Elements
import java.util.ArrayList;
public void main (String[] args){
   ArrayList<Integer> list=new ArrayList<Integer>();
   list.add(123);
   list.add(234);
   list.add(345);
   for(int i=0;i<list.size();i++){
       System.out.println(list.get(i));
   }
}
add an element of the specified type
public class demo {
	public static void main(String[] args) {
		ArrayList<Person> list = new ArrayList<Person>();
		list.add(new Person(18, "张三", "男"));
		list.add(new Person(58, "李四", "女"));
		list.add(new Person(28, "李宝林", "男"));
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}

Collection interface

The ArrayList class inherits from the abstract class AbstractList and implements the interface List, which in turn inherits from the Collection interface. That is, Collection is the root interface in the hierarchy.

Basic methods commonly used in the Collection interface

	public static void main(String[] args) {
		// Polymorphic parent class reference points to child class object
		Collection<String> coll = new ArrayList<String>();
		// add method of collection
		coll.add("Zhang San");
		coll.add("Li Si");
		coll.add("王五");
		System.out.println(coll);
		// set to array
		Object[] arr = coll.toArray();
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		// The remove method in the collection removes the specified element
		coll.remove("Li Si");
		System.out.println("Number of elements in the container after removal: " + coll.size());
		// The contains method in the collection determines whether the element exists in the method
		boolean b = coll.contains("李四");
		System.out.println(b);
		// The clear method in the collection clears the contents of the container
		coll.clear();
		System.out.println(coll);

	}

How to create a collection

Method 1: Collection<element type> variable name = new ArrayList<element type>(); //Can only store the element type specified in <>

Method 2: Collection variable name = new ArrayList(); //  The element type of the collection defaults to the Object type, that is, any type of element can be stored

Iterator iterator

The use of iterators is essentially a loop traversal, and can only be looped through, and cannot add, delete, or modify the collection.

In the collection, this method of taking elements is described in the iterator interface. The commonly used methods are:

hasNext () method: used to determine whether there is the next element in the collection to iterate. If it returns true, it means it can be iterated.

next () method: used to return the next element of the iteration and move the pointer back one place.

 

public static void main(String[] args) {
		Collection<String> coll = new HashSet<String>();
		coll.add("Hello World");
		coll.add("Hello, world");
		coll.add("Study hard and make progress every day");
		// The essence of the use of iterators is to loop through
		// Get the iterator object
	        Iterator<String> it = coll.iterator();
		// Determine if there is an element next in the collection hasNext()
               //loop through
		while(it.hasNext()){
		    String str=it.next();
		    System.out.println(str);
		 }
		// When it.hasNext() has been judged to be false, if you still want to fetch elements, an exception will be reported
		// java.util.NoSuchElementException
		// System.out.println(it.next());           

               //The iterator is used in the form of a for loop
		for (Iterator<String> it = coll.iterator(); it.hasNext();) {
			System.out.println(it.next());
		}
	}

 

  An abstract method iterator method is described in the Collection interface . All Collection subclasses implement this method and have their own iteration form.

   

Downcasting of collection elements

Elements of any type can be stored in the collection, but after the elements are stored, they will not be of the original data type and will be promoted to the Object type.

To extract it, you need to downcast.

Collection coll = new ArrayList();
coll.add("abc");
coll.add("aabbcc");
coll.add(1);
Iterator it = coll.iterator();
while (it.hasNext()) {
    //Because the elements are all promoted to Object type after they are stored in the collection
   //When you need to use the specific methods of the subclass object, you need to downcast
    String str = (String) it.next();
    System.out.println(str.length());
}
Note: If there are multiple objects stored in the collection, a type conversion exception will occur when downcasting is performed.

 At this point , generics are needed , and the Iterator interface can also use <> to control the type of iterative elements.

 

Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("aabbcc");
coll.add("shitcast");
Iterator<String> it = coll.iterator();
while (it.hasNext()) {
    String str = it.next();
//When using Iterator<String> to control the element type, there is no need to cast it. The obtained element is directly of type String
    System.out.println(str.length());
}

Note: The storage in the collection is actually the address of the object .

    Can primitive values ​​be stored in collections?

      The jdk1.5 version can be stored later. Because of the appearance of the basic type wrapper class, it provides an automatic boxing operation (basic type à object), so that the elements in the collection are the wrapper class objects of the basic value.

Enhanced for loop

//Enhanced version of for loop, also known as foreach, can only traverse arrays or collections, and cannot add, delete, or modify
// for(data type variable name: target container){output}
// The data type is the same as that of the target container .

		int[] arr = { 4, 2, 6, 3, 7, 1 };
                for (int i : arr) {
			System.out.println(i);
		}

Generics

Any type of element in a collection can be stored. When fetching, a runtime ClassCastException will be thrown if there is a forced cast . When using collections at this time, you should be clear about the types of elements in the collection. generics

class with generics

 

Definition format: modifier class class name < variable representing generic type > { } For example: public class ArrayList<String>{}

 

When creating an object, determine the generic type such as: ArrayList<String> list=new ArrayList<String>();

 

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo6 {
	public static void main(String[] args) {
		Collection<String> arr = new ArrayList<String>();
		arr.add("asd");
		arr.add("123");
		arr.add("Zhang San");
		String[] str = new String[arr.size()];
		// set to array
		String[] str1 = arr.toArray(str);
		for (String str2 : str1) {
			System.out.println(str2);
		}
		System.out.println("------------------");
		get(arr);
		Collection<Person> arr2 = new ArrayList<Person>();
		arr2.add(new Person(12, "张三", "男"));
		get(arr2);
	}
        //When defining a method, it is impossible to determine what the type in the specific collection is, so it can be represented by a wildcard 
// But once a generic wildcard is used, only the common methods in the Object class can be used, and the methods of the elements themselves in the collection cannot be used
	// wildcard?
	public static void get(Collection<?> coll) {
		Iterator<?> it = coll.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

 

generic qualification

 If you want to limit the types of elements in the collection to be printed, print only the specified types. To solve this problem, it is necessary to use generic constraints.

 

Limit the upper limit of generics:

 

Format: ? extends E

 

? represents an element that receives type E or a subtype of E

 

For example, generics are qualified as: ? extends Person

 

Then ? represents an element that receives a Person type or a Person subtype

 

Limit the lower bound of generics:

 

Format: ? super E

 

? represents an element that receives type E or a supertype of E

 

For example, generics are qualified as: ? super Student

 

Then ? represents the element that receives the Student type or the Student parent type

 

public static void main(String[] args) {
		ArrayList<Chef> arr1 = new ArrayList<Chef>();
		arr1.add(new Chef("老王", "23"));
		get(arr1);
		ArrayList<Fuwuyuan> arr2 = new ArrayList<Fuwuyuan>();
		arr2.add(new Fuwuyuan("老王", "23"));
		get(arr2);

	}
        //? extends the upper bound of class generics
	//? lower bound on super class generics

       //Using the upper limit of generics, you can call the work() method of the Person class, and then output the work method rewritten by the subclass
	public static void get(ArrayList<? extends Emp> arr) {
		Iterator<? extends Emp> it = arr.iterator();
		while (it.hasNext()) {
			it.next().work();
		}
	}


public static void main(String[] args) {
		ArrayList<Chef> arr1 = new ArrayList<Chef>();
		arr1.add(new Chef("老王", "23"));
		get(arr1);
		ArrayList<Object> arr2 = new ArrayList<Object>();
		arr2.add(new Fuwuyuan("老王", "23"));
		get(arr2);

	}
	//? lower bound on super class generics
        //The lower limit of the generic type can only receive elements of the Chef type or the parent type of Chef
       //Not all parent classes have a work() method, so the work method cannot be called here
	public static void get(ArrayList<? super Chef> arr) {
		Iterator<? super Chef> it = arr.iterator();
		while (it.hasNext()) {
			it.next();
		}
	}

 

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324475367&siteId=291194637