Java study notes 8-collection

1. Introduction

      A collection refers to a collection of concrete or abstract objects with certain properties. Among them, these objects constituting the set are called the elements of the set. That is: a whole composed of one or more certain elements.

Second, the role

存储对象的容器,将容器添加标签,使其只能存储某种对象类型。

3. Features

  • Can only be used to store objects;
  • Stored is a reference to the object;
  • Can store different types, unlimited number of data types;

Fourth, the difference between collection and array

长度区别:

  • Array fixed
  • Variable collection

内容区别:

  • The array can be a basic data type or a reference data type
  • Collection is a reference data type

元素内容:

  • Arrays can only store the same type
  • Collections can store different types

5. Classification (according to the implemented interface)

Insert picture description here
summary:

  • Set: Unordered, non-repeatable collection;
  • List: ordered, repeatable collection;
  • Map: key-value pair mapping, the key is unique, the value is not unique;

Six, detailed type

set

1. Introduction The
      set element guarantees that the uniqueness of the element relies on the equal() and hashCode() methods. When these two methods are not overridden in the created element, no one calls these two methods in the Object class. By default, the object() method compares whether the address values ​​are equal.
2. Features
Features: unordered, non-repeatable collection;
3. Classification
HashSet, TreeSet, LeakedHashSet
4. Type

HashSet
(1) Features:

  • Call hashCode() to see the same hash value,
  • Call equals() to compare with new elements, and remove duplicates (implementation of the underlying hash algorithm, high efficiency)

(2) Usage

  • Create a collection object (List is an interface, instantiate the interface by creating a subclass object), Set set=new HashSet()
  • Create element object
  • Add elements to the collection, add()
  • Loop through the collection and output

(3) Traverse

  • Ordinary for loop
  • Enhanced for loop
  • Iterator
public class Hast {
    
    
	public static void main(String[] args) {
    
    
//		Set set=new HashSet();//另一种调用集合方法
//		set.add("as");
//		set.add(12);
//		System.out.println(set);
		Set<Object> set1=new HashSet<Object>();//object为所有类的父类,就是说set里面可以添加任何类型元素
		set1.add(12);
		set1.add(21);
		set1.add("ss");//添加元素
		System.out.println(set1);
		set1.remove(12);//移除元素,显示剩余元素
		System.out.println(set1);
		System.out.println(set1.contains(12));//判断集合是否包含该元素
		set1.add(true);
		int ss=set1.size();//显示集合中有多少元素
		System.out.println(ss);
		Iterator sl=set1.iterator();//使用迭代器遍历集合
		while (sl.hasNext()) {
    
    
			System.out.println(sl.next());	
		}
		//for each迭代数据
		for (Object obj : set1) {
    
    //把set的每一个数据取出来赋值给obj,直到循环结束
		System.out.println(obj);
		}
		
		
		Set<String> set2=new HashSet<String>();//指定集合中只能放string数据类型
		set2.add("s1");
		set2.clear();//清空集合
		set2.add("s2");
		System.out.println(set2);
		
	}

}

TreeSet
features: automatically arrange elements in ascending order (implementation of the underlying binary tree)

public class Tset {
    
    
	public static void main(String[] args) {
    
    
		Set<Object> ss=new TreeSet<Object>();
		ss.add("a");
		ss.add("c");
		ss.add("a");
		ss.add("s");
		ss.add("o");
		System.out.println(ss);//按照自然排序
		
		
		Set<Integer> ss1=new  TreeSet<Integer>();
		ss1.add(2);
		ss1.add(1);
		ss1.add(4);
		ss1.add(3);
		for (Integer i:ss1) {
    
    
			System.out.println(i);
		}
	}
}

List

1. Features
Features: ordered and repeatable collections
2. Classified
ArrayList, LinkedList, Vector
3. Types
ArrayList
(1) Features: bottom dynamic array, fast query, slow addition and deletion (same array), unsafe thread, high efficiency.

(2) Usage

  • Create a collection object (List is an interface, the instantiation of the interface is completed by creating a subclass object), List list=new ArrayList()
  • Create element object
  • Add elements to the collection, add()
  • Loop through the collection and output; the iterator must be implemented by calling the list iterator when iterating.
public class ALise {
    
    
	public static void main(String[] args) {
    
    
		List<String> list=new ArrayList<String>();//指定插入集合类型为string
		list.add("d");
		list.add("e");//list允许元素重复
		list.add("a");
		list.add("d");
		list.add("q");
		list.add("k");
		System.out.println(list);
		System.out.println(list.get(2));//通过索引下标来访问指定位置元素
		
		list.add(0,"e");//在指定索引下标位置插入数据
		System.out.println(list);
		System.out.println(list.indexOf("d"));//获取指定元素在集合中第一次出现的索引下标
		System.out.println(list.lastIndexOf("d"));//获取指定元素在集合中最后一次出现的索引下标
		list.set(1, "w");//根据指定的索引下标修改元素
		List<String> seList=list.subList(1, 4);取索引下标在大于等于2小于4的元素
		System.out.println(seList);
		System.out.println(list.size());
	}
}

LinkedList
features: the bottom layer is a link, the query is slow, the addition and deletion is fast, the thread is not safe, and the efficiency is high.
Vector
features: fast query, slow addition and deletion, thread safety, and low efficiency.

Map

1. Function: used for data with mapping relationship

2、分类:HashMap、Hashtable、TreeMap

3. Type
HashMap
(1) Features: The bottom layer is hash calculation and distribution, which is targeted at keys

(2) Usage

  • Create a collection object, Map<Interger,Object> map=new HashMap<>();
  • Create element object
  • Add elements to the collection, put()
  • Loop through the collection and output: 1. Get the key of all elements: keySet(); 2. Traverse the keySet: iterator(); 3. Get the value by key: get().

TreeMap
features: the bottom layer is a binary tree algorithm, targeting keys

public class Test6 {
    
    
	public static void main(String[] args) {
    
    
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("b", 1);//添加数据
		map.put("c", 2);
		map.put("e", 2);
		System.out.println(map);
		
		System.out.println(map.get("b"));//根据key取值
		
		map.remove("c");//根据key移除键值对
		System.out.println(map);
//		
		System.out.println(map.size());//map集合的长度
		
		System.out.println(map.containsKey("a"));//判断当前的map集合是否包含指定的key
		
		System.out.println(map.containsValue(10));//判断当前的map集合是否包含指定的value
		
//		map.clear();//清空集合
		
		Set<String> keys = map.keySet();//获取map集合的key的集合
		
		map.values();//获取集合的所有value值
		
		//遍历map集合,通过map.keySet();
		for(String key : keys){
    
    
			System.out.println("key: " + key + ", value: " + map.get(key));
		}
		
		//通过map.entrySet();遍历map集合
		Set<Entry<String, Integer>> entrys = map.entrySet();
		for(Entry<String, Integer> en : entrys){
    
    			System.out.println("key: " + en.getKey() + ", value: " + en.getValue());
		}
		
		//TreeMap的自然排序是字典排序
		Map<Integer,String> map1 = new TreeMap<Integer, String>();
		map1.put(4, "a");
		map1.put(2, "a");
		map1.put(3, "a");
		map1.put(1, "a");
		
		System.out.println(map1);
		
		Map<String,String> map2 = new TreeMap<String, String>();
		map2.put("b", "b");
		map2.put("c", "c");
		map2.put("d", "d");
		map2.put("a", "a");
		map2.put("ab", "ab");
		map2.put("1", "ab");
		map2.put("10", "ab");
		
		System.out.println(map2);
		
	}
}

Seven, tools

1. Function
Operate Set, List, Map, sort, query, modify and other operations; also provide methods for setting immutable collection objects and achieving synchronization control for collection objects;
2. Common member methods

function effect
reverse(List) Reverse the order of elements in the collection
shuffle(List) Randomly sort collection elements
sort(List) Ascending
sort(List,Comparator) Sort the collection according to the order of the specified Comparator
swap(List, int , int) The element at i and the element at j of the specified set are exchanged
Object max(Collection) According to the natural order of the elements, returns the largest element in the given set
Object max(Collection,Comparator) According to the order specified by the Comparator, return the largest element in the given set
Object min(Collection) Returns the smallest element in the given set
Object min(Collection,Comparator) According to the order specified by Comparator, return the smallest element in the given set
int frequency(Collection,Object) Returns the number of occurrences of the specified element in the specified collection
boolean replaceAll(List list,Object oldVal,Object newVal) Replace all old values ​​of the List object with new values
public class Test7 {
    
    
	public static void main(String[] args) {
    
    
		List<String> list = new ArrayList<String>();
		list.add("b");
		list.add("cd");
		list.add("ca");
		list.add("a");
		list.add("a");
		list.add("1");
		
		System.out.println(list);
		
		Collections.reverse(list);//反转 List 中元素的顺序
		System.out.println(list);
		
		Collections.shuffle(list);//对 List 集合元素进行随机排序
		System.out.println(list);
//		
		Collections.sort(list);//list集合字典升序排序
		System.out.println(list);
		
		System.out.println(Collections.frequency(list, "x"));//返回指定集合中指定元素的出现次数
		
		Collections.replaceAll(list, "b", "bb");//使用新值替换 List 对象的所有旧值
		
		System.out.println(list);
		
		Collections.swap(list, 0, 4);//将指定 list 集合中的 i 处元素和 j 处元素进行交换
		System.out.println(list);
		
		System.out.println(Collections.max(list));//list中最大值
		System.out.println(Collections.min(list));//list中最小值
		
	}
}

Guess you like

Origin blog.csdn.net/qq_45913017/article/details/112998890