Chapter 12 Collection Class

Collection class overview

The difference between collection classes and arrays is: the length of arrays is fixed, while the length of collections isvariable; Arrays are used to store basic types of data, and collections are used to store references to objects.

Commonly used collections

List collection, Set collection and Map collection

The List collection and the Set collection inherit the Coolection interface, and each interface also provides different implementation classes. The relationship is as follows:

 

Collection interface

Collection interface is the root interface in the hierarchy, and the units that make up Collection become elements a>

The method to traverse the collection is as follows:

 

Example 12.1

 

The running results are as follows:

List collection

The List collection inherits the Collection interface and therefore contains all methods in the Collection interface.

The Lise interface also defines the following two very important methods:

get(int index): Get the element at the specified index position

set(int index,Object obj): Modify the object at the specified index position in the collection to the specified object 

Add: add()

Get: get()

Delete: remove()

Change: set()

Implementation class of List interface

Commonly used implementation classes of the List interface include the ArrayList class and the LinkedList class:

The ArrayList class implements a mutable array, allowing storage of all elements, including null, and fast random access to the collection based on index position. The disadvantage is that the speed of inserting or deleting objects to the specified index position is slow
The LinkedList class uses a linked list structure to save objects. The advantage of this structure is that it facilitates the insertion and deletion of objects from the collection. When objects need to be inserted or deleted from a collection, the List collection implemented using the LinkedList class is more efficient; however, for objects in random access, the List collection implemented using the LinkedList class is less efficient.
 

The code for the LinkedList class to instantiate the List collection respectively is as follows:

List<E>list = new ArrayList<>(); //The following <E> generic can be omitted

List<E>list2= new LinkedList<>();

 Example 1

The running results are as follows:

package a;
 
import java.util.ArrayList;
import java.util.List;
 
public class Gather {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String>list = new ArrayList<>();  //创建集合对象
	    list.add("a");       //向集合添加元素
	    list.add("b");
	    list.add("c");
	    int i = (int)(Math.random()*list.size());  //获得0~2的随机数
	    System.out.println("随机获取集合中的元素:"+list.get(i));
	    list.remove(2);  //将指定索引位置的元素从集合中移除
	    System.out.println("将索引是’2‘的元素从集合移除后,集合中的元素是:");
	    for (int j = 0;j<list.size();j++) {    //循环遍历集合
	    	System.out.println(list.get(j));
	    }
	}
 
}

2 other easier methods

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Gather {//创建Gather类

	public static void main(String[] args) {//主方法
		List<String>list = new ArrayList<>();//创建集合对象
		list.add("a");//向集合添加元素
		list.add("b");
		list.add("c");
		list.add("d");
		int i = (int)(Math.random()*list.size());//获得0~2的随机数
		System.out.println("随机获取集合中的元素:"+list.get(i));
		list.remove(2);//将指定索引位置的元素从集合中移除
		for(int j = 0;j < list.size();j++) {
			System.out.println(list.get(j));
		}
		System.out.println("将索引是2的元素从集合移除后,集合中的元素是:");
		for(String temp : list) {//循环比遍历集合
			System.out.println(temp);
		}
		System.out.println("Iterator迭代打印内容:");
		Iterator<String> it = list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
	
	

}

 The running results are as follows:

Set collection

The objects in the Set collection are not ordered in a specific way, but the Set collection cannot contain duplicate objects.

Commonly used implementation classes of the Set interface include the HasgSet class and the TreeSet class:

HasgSet is a sequence collection. This class implements the Set interface. It does not guarantee the iteration order of the Set collection. In particular, it does not guarantee that the order is permanent. This class allows the use of null elements.

TreeSet is a collection of numbers. It not only implements the Set interface, but also implements the java.util.SortedSet interface. Therefore, the Set collection implemented by the TreeSet class is sorted incrementally in the natural order when traversing the collection. It can also be sorted incrementally according to the specified comparator, that is, it can be sorted by comparison. The implementer sorts the objects in the Set collection implemented using the TreeSet class.

New methods added to the TreeSet class:

 Example 12.3

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {//创建TreeSetTest类

	public static void main(String[] args) {
		Set<Integer>set = new HashSet<>();//使用TreeSet类创建Set集合对象
		set.add(-5);
		set.add(-7);
		set.add(10);
		set.add(6);
		set.add(3);
		Iterator<Integer>it = set.iterator();//创建Iterator迭代器对象
		System.out.println("Set集合类中的元素");//提示信息
		while(it.hasNext()) {//遍历并输出Set集合中的元素
			System.out.println(it.next()+"");
		}
	}

}

The running results are as follows:

Map collection

The Map collection does not inherit the Collection interface, but provides a mapping from key to value. The Map collection cannot contain the same key, and each key can only map one value.

Map interface

The Map interface provides objects that map keys to values. A mapping cannot contain duplicate keys, and each key can only be mapped to at most one value. In addition to the common methods of collections, other special methods are as follows:

 

Implementation class of Map interface

Commonly used implementation classes of the Map interface include the HashMap class and the TreeMap class:

 The HashMap class is an implementation of the Map interface based on a hash table. This implementation provides all optional mapping operations and allows the use of null and null values, but the uniqueness of the key must be guaranteed. The HashMap class uses a hash table to quickly search for its internal mapping relationships. This class does not guarantee the order of the mapping, and in particular it does not guarantee that the order is immutable.
The TreeMap class not only implements the Map interface, but also implements the java.utli.SortedMap interface, so the mapping relationships in the collection have a certain order. However, when it comes to adding, deleting and locating mapping relationships, the performance of the TreeMap class is slightly worse than that of the HashMap class. Since the mapping relationships in the Map collection implemented by the TreeMap class are arranged in a certain order according to the key objects, the key objects are not allowed to be null.
Example 12.4

package b;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapTest {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String,String>map=new HashMap<>();   //创建Map集合对象
		map.put("ISBN-978654","Java从入门到精通");   //向Map集合中添加元素
		map.put("ISBN-978361","Android从入门到精通");
		map.put("ISBN-978893","21天学Android");
		map.put("ISBN-978756","21天学Java");
		Set<String>set=map.keySet();    //构建Map集合中所有的key的Set集合
		Iterator<String> it =set.iterator();    //创建Iterator迭代器
		System.out.println("key值:");
		while(it.hasNext()) {     //遍历并输出Map集合中的key值
			System.out.print(it.next()+" ");
		}
		Collection<String> coll =map.values();    //构建Map集合中所有value值的集合
		it=coll.iterator();
		System.out.println("\nuvalue值:"); 
		while(it.hasNext()) {       //遍历并输出Map集合中的value值
			System.out.print(it.next()+" ");
		}
	}
 
}

The running results are as follows:

Easy way

package b;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapTest {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String,String>map=new HashMap<>();   //创建Map集合对象
		map.put("ISBN-978654","Java从入门到精通");   //向Map集合中添加元素
		map.put("ISBN-978361","Android从入门到精通");
		map.put("ISBN-978893","21天学Android");
		map.put("ISBN-978756","21天学Java");
		Set<String>set=map.keySet();    //构建Map集合中所有的key的Set集合
		Iterator<String> it =set.iterator();    //创建Iterator迭代器
		
		while(it.hasNext()) {     //遍历并输出Map集合中的key值
			String key = it.next();
			String value =map.get(key);
			System.out.println(key +" "+value);
		}
		
		}
	}

 The running results are as follows:

Guess you like

Origin blog.csdn.net/2301_76549195/article/details/132944088