Collection basics

Collection (Collection)

1. Generics

1. Concept

Generics (Generics) is a new feature of JDK1.5. It is actually a [syntax sugar]. It is essentially a small means provided by the compiler to provide better readability. Tips, the virtual machine level is not There is a so-called generic concept.

2. Function

  • Through the definition of generic syntax, the types of collection elements are constrained, security checks are performed, and errors are displayed at compile time;
  • Code is more versatile
  • Generics can improve the readability of program code, but they are just syntactic sugar (such things are deleted after compilation and do not appear in the final source code) and have no impact on the performance of the JVM runtime.

3. Generic declaration (location of use)

  • Generics can be used on the return values ​​of interfaces, classes, and methods

    java.util.List generic interface/class

    public interface Collection<E> {}

  • Generic method declaration

    public <E> void print(E e){}

    Declaring an E before the method return value indicates <E>that the E appearing later is a generic type, not an ordinary Java variable.

4. Common names

  • E -Element (used in collections, because collections store elements)
  • T-Type (Java class)
  • K-Key (key)
  • V -Value (value)
  • N -Number (numeric type)
  • ? -Indicates an undefined java type

5. Purpose

  1. Compile time type checking
  2. Code is more versatile
package cn.tonyoliver.generics;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 这个类用来测试泛型用途一:编译时做类型检查
 * 
 * @author Tony
 *
 */
public class Test01_Generics {
    
    
	public static void main(String[] args) {
    
    
		int[] a = new int[3];
		a[0] = 1;
		a[1] = 2;
		// int类型的数组,规定了数组里的数据类型,类型不对就报错
//		a[2] = "hello";

		// 1,泛型的标志<>
		// 2,泛型的好处:规定了数据的类型,不能想放什么类型的数据就放什么类型的,要遵守泛型规定的类型
		// 3,泛型的数据类型只能是引用类型,不能是基本类型
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		// 4,如果类型不对,把运行期才会报的错ClassCastException直接在编译时期就报出来
//		list.add("a");//The method add(Integer) in the type List<Integer> is not applicable for the arguments (String)

//		Iterator it = list.iterator();
//		while(it.hasNext()) {
    
    
//			Integer s = (Integer)it.next();
//			System.out.println(s);
//		}
		Iterator<Integer> it = list.iterator();
		while (it.hasNext()) {
    
    
			Integer s = it.next();
			System.out.println(s);
		}
	}
}

package cn.tonyoliver.generics;

/**
 * 这个类用来测试泛型用途一:代码通用性更强
 * 
 * @author Tony
 *
 */
public class Test02_Generics {
    
    
	public static void main(String[] args) {
    
    
		// traditon();// 传统方法
		generics();// 泛型方法
	}

	// 传统方法:通过重载多态实现,方法同名,参数类型不同
	private static void traditon() {
    
    
		Integer[] scores = new Integer[] {
    
     100, 98, 80 };
		String[] names = new String[] {
    
     "语文", "数学", "英语" };

		Test02_Generics.print(scores);
		Test02_Generics.print(names);
	}

	private static void print(Integer[] ss) {
    
    
		for (Integer d : ss) {
    
    
			System.out.println(d);
		}
	}

	private static void print(String[] dd) {
    
    
		for (String s : dd) {
    
    
			System.out.println(s);
		}
	}

	// 泛型方法
	private static void generics() {
    
    
		Integer[] scores = new Integer[] {
    
     100, 98, 80 };
		String[] names = new String[] {
    
     "语文", "数学", "英语" };
		Double[] moneys = new Double[] {
    
     10.2, 20.2, 30.3 };

		Test02_Generics.print(scores);
		Test02_Generics.print(names);
		Test02_Generics.print(moneys);
	}

	public static <E> void print(E[] arr) {
    
    
		for (E e : arr) {
    
    
			System.out.println(e);
		}
	}

}

6. Type erasure

Generics only survive during compilation, and are killed after compilation. When they are actually run, they are replaced by Object in most cases.

It uses the powerful reflection function provided by jdk.

package cn.tonyoliver.generics;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 这个类用来测试类型擦除
 * 
 * @author Tony
 *
 */
public class Test03_GenericsRemove {
    
    
	public static void main(String[] args) throws Exception {
    
    
		List<Integer> list = new ArrayList<Integer>();

		// 1,编译器按泛型检查,类型报错,这是在编译时期
//		list.add("chen");//The method add(Integer) in the type List<Integer> is not applicable for the arguments (String)

		// 2,但在实际运行时,泛型的地方就被替代为通用类型Object
		Class<?> clazz = list.getClass();
		Method m = clazz.getDeclaredMethod("add", Object.class);

		// 3,利用反射得到的对象是运行时对象,就可以设置非整型的数据
		m.invoke(list, "chen");

		System.out.println(list.get(0));
	}
}


2. Collection

1 Overview

  1. In the current program, we can put multiple data into an array and store it. The array is used as a container for storing multiple data;
  2. Advantages and disadvantages of arrays: the data type is required to be a single type + the length of the array is immutable once created + the traversal method is single + not suitable for insertion and deletion
  3. There are many kinds of tool classes in the collection, all of which have a very strict inheritance structure. The top-level parent class is an interface Collection interface.

2. Inheritance structure of collections

The formation of the upper layer mainly extracts the common features of the lower layer to form an abstract layer;

The lower layer mainly uses various methods provided by the upper layer.

Insert image description here

3. Collection interface

1. Collection interface

The root interface in the Collection hierarchy. Collection represents a set of objects, which are also called elements of Collection. Some Collections allow duplicate elements, while others do not. Some Collections are ordered and some are unordered.

  • List interface: data is ordered and can be repeated
    • ArrayList subclass
    • LinkedList subclass
  • Set interface: data is unordered and duplicate values ​​cannot be stored
    • HashSet
  • Map interface: key-value pair storage data
    • HashMap
  • Collections tool class

2. Commonly used methods

  • boolean add(E e): add element;
  • boolean addAll(Collection c): Add a small collection to a large collection;
  • boolean contains(Object o): Returns true if this collection contains the specified element;
  • boolean isEmpty(): Returns true if this collection has no elements;
  • Iterator <E>iterator(): Returns an iterator that iterates over the elements of this collection;
  • boolean remove(Object o): Removes a single instance of the specified element from this collection;
  • int size(): Returns the number of elements in the collection;
  • Object[] toArray(): returns object elements;
  • Object[] toArray(): Returns an array containing all elements in this collection.
package cn.tonyoliver.collection;

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

/**
 * 这个类用来测试Collection接口
 * 
 * @author Tony
 *
 */
public class Test04_Collection {
    
    
	public static void main(String[] args) {
    
    
		// 1,创建对象
		// ArrayList is a raw type. References to generic type ArrayList<E> should be
		// parameterized
		// ArrayList是原始类型。对泛型类型ArrayList<E>的引用应参数化
		// Collection c = new ArrayList();
		Collection<String> c = new ArrayList<>();

		// 2,调用方法
		c.add("杨幂");
		c.add("赵丽颖");
		c.add("皮皮虾");
//		c.add(123);//添加元素的类型,没有通过泛型的类型检查,会直接报错

		System.out.println(c);
		// c.clear();
		System.out.println(c.contains("杨幂"));// true,判断集合中是否包含指定的元素
		System.out.println(c.equals("杨幂"));// false,判断集合是否和指定元素相等
		System.out.println(c.hashCode());// 获取集合在内存中的哈希码值
		System.out.println(c.isEmpty());// 判断集合是否为空
		System.out.println(c.size());// 获取集合中元素个数(集合的长度)
		System.out.println(c.remove("赵丽颖"));// 移除集合中的指定元素
		System.out.println("c" + c);

		Object[] objs = c.toArray();// 把集合转成数组
		System.out.println(Arrays.toString(objs));
		// 集合间的操作
		Collection<String> c2 = new ArrayList<>();
		c2.add("周杰伦");
		c2.add("杨幂");
		c2.add("赵丽颖");
		System.out.println(c.addAll(c2));// 向c集合中加入c2的数据
		System.out.println("c" + c);
		System.out.println(c.containsAll(c2));// 判断c中是否包含c2的所有元素
		// System.out.println(c.removeAll(c2));//获取c和c2的差集
		System.out.println("--c" + c);
		System.out.println(c.retainAll(c2));
		System.out.println("++c" + c);// 获取c和c2的交集

		// 集合的迭代
		// Iterator是一个接口,专门用来 迭代集合里的元素
		Iterator<String> it = c.iterator();
		while (it.hasNext()) {
    
    
			System.out.println(it.next() + "===");
		}
	}
}

4. List interface

It is a sub-interface of the collection interface and inherits all the functions of the Collection interface.

1. Concept

An ordered collection (also called a sequence). Users of this interface have precise control over where each element in the list is inserted. Users can access elements based on their integer index (position in the list) and search for elements in the list.

2. Features

  • Data is in order;
  • Allows storage of duplicate elements;
  • Elements have integer indexes;
  • Multiple nulls can be stored.

3. Commonly used methods

There are methods inherited from the Collection interface, and there can also be unique methods.

  • boolean add(E e): add element;
  • boolean addAll(Collection c): Add a small collection to a large collection;
  • boolean contains(Object o): Returns true if this collection contains the specified element;
  • boolean isEmpty(): Returns true if this collection has no elements;
  • Iterator <E>iterator(): Returns an iterator that iterates over the elements of this collection;
  • boolean remove(Object o): Removes a single instance of the specified element from this collection;
  • int size(): Returns the number of elements in the collection;
  • Object[] toArray(): returns object elements;
  • Object[] toArray(): Returns an array containing all elements in this collection.

The following are the unique methods of List

  • void add(int index, E element)
    inserts the specified element at the specified position in the list (optional operation).
  • boolean addAll(int index, Collection<? extends E> c)
    inserts all elements in the specified collection into the specified position in the list (optional operation).
  • E get(int index)
    returns the element at the specified position in the list.
  • int indexOf(Object o)
    returns the index of the first occurrence of the specified element in this list; if this list does not contain the element, it returns -1.
  • int lastIndexOf(Object o)
    Returns the index of the last occurrence of the specified element in this list; if the list does not contain this element, returns -1.
  • ListIterator listIterator()
    returns a list iterator of the elements of this list (in appropriate order).
  • ListIterator listIterator(int index)
    Returns a list iterator of the elements in the list (in appropriate order), starting at the specified position in the list.
  • E remove(int index)
    removes the element at the specified position in the list (optional operation).
  • E set(int index, E element)
    replaces the element at the specified position in the list with the specified element (optional operation).
  • List subList(int fromIndex, int toIndex)
    returns a partial view of the list between the specified fromIndex (inclusive) and toIndex (exclusive).

ListIterator<E>接口是Iterator<E>的子接口,子接口丰富了遍历方式,除了可以顺序遍历,还可以逆向向前遍历。

List traversal method

  • Iterator traverse
  • ListIterator traversal
  • for loop traverses
  • for-each loop traversal

test

package cn.tonyoliver.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * 这个类用来测试List接口
 * 
 * @author Tony
 *
 */
public class Test05_List {
    
    
	public static void main(String[] args) {
    
    
		// 1,创建对象--泛型用来约束集合中的元素类型,但是只能写引用类型,不能写基本类型
		List<Integer> list = new ArrayList<>();

		list.add(1);
		list.add(2);
		list.add(3);
		list.add(1);
		list.add(2);
		list.add(null);

		// 2,特点:元素有序+允许重复元素,可以存放多个null
		System.out.println(list);

		// 3,调用方法
		// --继承自Collection的方法们
		List<Integer> list2 = new ArrayList<>();
		list2.add(10);
		System.out.println(list.addAll(list2));
		System.out.println(list.contains(10));
		System.out.println(list.isEmpty());
		System.out.println(list.remove(1));
		System.out.println(Arrays.toString(list.toArray()));

		// List的特有方法们--是可以根据下标操作的方法们
		list.add(2, 100);
		System.out.println(list);// 在指定下标处插入指定的元素
		System.out.println(list.get(5));// 获取下标为5的位置对应的元素
		System.out.println(list.indexOf(2));// 获取数字2第一次出现的索引值
		System.out.println(list.lastIndexOf(1));// 获取数字1最后一次出现的索引
		System.out.println(list.remove(3));// 删除下标为3的元素
		System.out.println(list);

		System.out.println(list.set(3, 99));
		System.out.println(list);

		List<Integer> list3 = list.subList(2, 5);
		System.out.println(list3);

		// List的特有方法---迭代List集合
		// Collection接口的方法:Iterator<E> iterator()
		Iterator<Integer> it = list.iterator();
		while (it.hasNext()) {
    
    
			System.out.print(it.next() + " ");
		}
		// List接口的特有方法:ListIterator<E> listIterator()
		ListIterator<Integer> it2 = list.listIterator();
		while (it.hasNext()) {
    
    
			System.out.println(it2.next());
		}

		System.out.println();
		for (int i = 0; i < list.size(); i++) {
    
    
			System.out.print(list.get(i) + "---");
		}
		// 增强for循环 --foreach循环--用来优化普通的for循环,可以用于遍历数组或者collection集合的,好处是高效且语法简洁
		// 语法:for(遍历得到的数据类型 变量名:想要遍历的数组|Collection集合){循环体}
		for (Integer in : list) {
    
    
			System.out.println(in);
		}
	}
}




5. ArrayList implementation class

1. Concept

ArrayList is the implementation class of the List interface. You can use the functions of List or Collection.

2. Features

  • The bottom layer is an array structure for easy query.

ListImplementation of the interface for variable-sized arrays. All optional list operations are implemented and nullall elements including are allowed. In addition to implementing Listthe interface, this class also provides methods to manipulate the size of the array used internally to store the list.

3. Create objects

  • ArrayList()
    constructs an empty list with an initial capacity of 10. (jdk1.6)
    - jdk1.6 directly creates an array with a capacity of 10 when an ArrayList object is created;
    - jdk1.8 creates an empty array when an ArrayList object is created. To optimize memory, capacity expansion begins when the first element is added.

test

package cn.tonyoliver.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * 测试ArrayList实现类
 * 
 * @author Tony
 *
 */
public class Test06_ArrayList {
    
    
	public static void main(String[] args) {
    
    
		// 1,创建对象
		ArrayList<Integer> list = new ArrayList<>();

		list.add(1);
		list.add(2);
		list.add(3);
		list.add(1);
		list.add(2);
		list.add(null);

		// 2,调用方法
		// --继承自Collection接口的方法们
		ArrayList<Integer> list2 = new ArrayList<>();
		list2.add(10);
		System.out.println(list.addAll(list2));
		System.out.println(list.contains(10));
		System.out.println(list.isEmpty());
		System.out.println(list.remove(1));
		System.out.println(Arrays.toString(list.toArray()));

		// --继承自List接口的方法们
		list.add(2, 100);
		System.out.println(list);
		System.out.println(list.get(5));
		System.out.println(list.indexOf(2));
		System.out.println(list.lastIndexOf(1));
		System.out.println(list.remove(3));
		System.out.println(list);

		System.out.println(list.set(3, 99));
		System.out.println(list);

		List<Integer> list3 = list.subList(2, 5);
		System.out.println(list3);

		Iterator<Integer> it = list.iterator();
		while (it.hasNext()) {
    
    
			System.out.println(it.next());
		}
		ListIterator<Integer> it2 = list.listIterator();
		while (it2.hasNext()) {
    
    
			System.out.println(it2.next());
		}
		for (Integer it3 : list) {
    
    
			System.out.println(it3);
		}
	}
}

6. LinkedList implementation class

1. Concept

It is the implementation class of List interface. You can also use all the methods of List interface and Collection interface, and you can also extend the functions.

2. Features

  • The bottom layer is a linked list structure (suitable for additions and deletions)
  • Like the List interface, it can be repeated, ordered, null can be stored, and has subscripts.

3. Create objects

LinkedList()
constructs an empty list.

4. Commonly used methods

  • void addFirst(E e)
  • void addLast(E e)
  • E getFirst()
  • E getLast()
  • E removeFirst()
  • E removeLast()
  • boolean offerFirst(E e)
  • boolean offerLast(E e)
  • E peekFirst()
  • E peekLast()
  • E pollFirst()
  • E pollLast()
package cn.tedu.api;

import java.util.LinkedList;

/**
 * 这个类用来测试LinkedList
 */
public class Test02_LinkedList {
    
    
    public static void main(String[] args) {
    
    
        //1,创建对象
        LinkedList<Integer> list = new LinkedList<>();
        //2,调用方法
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        //TODO特有方法 -- 对首尾元素的操作
        list.addFirst(100);
        list.addLast(200);

        System.out.println(list.getFirst());//获取首元素
        System.out.println(list.getLast());//获取尾元素
        System.out.println(list.removeFirst());//移除首元素并返回首元素
        System.out.println(list.removeLast());//移除尾元素并返回尾元素
    }
}

7. Set interface

1 Overview

Inherits from the Collection interface, so you can use all methods of the parent interface Collection

2. Features

  • Elements cannot be repeated, and only one null can be stored.
  • The elements are unordered and have no subscripts
  • Mainly used for deduplication

3. Commonly used methods

Iterate over Set collection

package cn.tedu.api;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 这个类用来测试Set接口
 */
public class Test03_Set {
    
    
    public static void main(String[] args) {
    
    
        //1,创建对象
        Set<Integer> set = new HashSet<>();
        // 特点:Set无序  +  不能重复  +  没有下标  +  存null
        set.add(90);
        set.add(6);
        set.add(56);
        set.add(56);
        set.add(33);
        set.add(null);

        // 迭代Set集合
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
    
    
            System.out.println(it.next());
        }
        // for-each 迭代
        for (Integer it2: set) {
    
    
            System.out.println(it2);
         }
    }
}

8. HashSet implementation class

1. Concept

It is the implementation class of the Set interface, and you can use the methods of the Set interface;
the bottom layer is a 哈希表structure.

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

2. Create objects

HashSet()
constructs a new empty set; supported HashMap instances have default initial capacity (16) and load factor (0.75).

package cn.tedu.api;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 这个类用来测试Set接口
 */
public class Test03_Set {
    
    
    public static void main(String[] args) {
    
    
        //1,创建对象
        Set<Integer> set = new HashSet<>();
        // 特点:Set无序  +  不能重复  +  没有下标  +  存null
        set.add(90);
        set.add(6);
        set.add(56);
        set.add(56);
        set.add(33);
        set.add(null);

        // 迭代Set集合
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
    
    
            Integer in = it.next();//取数据 + 挪动指针
            //TODO 如果取到null调用null.XXX一定会报空指针异常NullPointerException
            //加一个判断条件可以有效的防止空指针异常
            if(in != null) {
    
    
                System.out.println(in.toString());
            }
        }
        // for-each 迭代
        for (Integer it2: set) {
    
    
            System.out.println(it2);
         }
    }
}

Guess you like

Origin blog.csdn.net/weixin_45015214/article/details/109292953