[Java study notes] List interface and its implementation class

table of Contents

1. Features of List Collection

2. The unique functions of the List collection

2.1 Add function

2.2 Get function

2.3 Delete function

2.4 List iterator

 2.5 Modify function

3. Causes and solutions of concurrent modification exceptions

4. Unique traversal function of List collection

5. The characteristics of the three subcategories of List

6.ArrayList case

6.1 Store string and traverse

6.2 Store custom objects and traverse

7. The unique functions of Vector

7.1 Add function

7.2 Get function

8. Unique functions of LinkedList

8.1 Add function

8.2 Get function

8.3 Delete function


1. Features of List Collection

The objects in the collection are sorted according to the index position, and there can be duplicate objects.

2. The unique functions of the List collection

2.1 Add function

  • void add(int index, Object element): add an element at the specified position

2.2 Get function

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

2.3 Delete function

  • Object remove(int index): delete the element according to the index and return the deleted element

2.4 List iterator

  • ListIterator listIterator(): List collection unique iterator, this iterator inherits the Iterator iterator, so you can directly use the hasNext() and next() methods. List iterators have the following unique functions:
    • boolean hasPrevious(): Determine whether there are elements
    • Object previous(): Get the previous element 

For specific usage, refer to the following code:

package com.hw.list;

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

/**
 * 列表迭代器 ListIterator
 * 		listIterator():List集合特有的迭代器,该迭代器继承了Iterator迭代器,所以可以直接使用hasNext()和next()方法。
 * 
 * 特有功能: 
 * 		Object previous():获取上一个元素 
 * 		boolean hasPrevious():判断是否有元素
 * 
 * @author HW
 * 
 */
public class ListDemo2 {
	public static void main(String[] args) {
		// 创建集合对象
		List<String> list = new ArrayList<String>();

		// 添加元素
		list.add("Jmeter");
		list.add("Selenium");
		list.add("AirTest");
		
		// 遍历集合
		// 通过集合对象获取列表迭代器对象
		ListIterator<String> lit = list.listIterator();
		while (lit.hasNext()) {
			System.out.println(lit.next());
		}
		
		System.out.println("==========");
		
		// 逆向遍历集合,前提是必须先正向遍历,才能逆向遍历,所以一般无意义,不使用。
		while(lit.hasPrevious()){
			System.out.println(lit.previous());
		}
	}
}

The results of the operation are as follows:

Jmeter
Selenium
AirTest
==========
AirTest
Selenium
Jmeter

 2.5 Modify function

  • Object set(int index, Object element): modify the element according to the index and return the modified element

For specific usage of the unique functions of the List collection, refer to the following code:

// 创建集合对象
List<String> list = new ArrayList<String>();
		
// 添加元素
list.add("Jmeter");
list.add("Selenium");
list.add("AirTest");
		
System.out.println("原始数据:" + list);
		
// void add(int index,Object element):在指定位置添加元素
list.add(1, "Python");
		
System.out.println("在索引为1的位置添加元素后:" + list);
		
// Object get(int index):获取指定位置的元素
System.out.println("获取索引为2的元素:" + list.get(2));
		
System.out.println("修改元素前:" + list);
		
// Object set(int index,Object element):根据索引修改元素,返回被修饰的元素
System.out.println("被修改的元素:" + list.set(3, "Fiddler"));
		
System.out.println("修改元素后:" + list);
		
// Object remove(int index):根据索引删除元素,返回被删除的元素
System.out.println("删除索引为0的元素:" + list.remove(0));
		
System.out.println("最终元素:" + list);

The results of the operation are as follows:

原始数据:[Jmeter, Selenium, AirTest]
在索引为1的位置添加元素后:[Jmeter, Python, Selenium, AirTest]
获取索引为2的元素:Selenium
修改元素前:[Jmeter, Python, Selenium, AirTest]
被修改的元素:AirTest
修改元素后:[Jmeter, Python, Selenium, Fiddler]
删除索引为0的元素:Jmeter
最终元素:[Python, Selenium, Fiddler]

3. Causes and solutions of concurrent modification exceptions

Requirement: There is a collection [Hello, World, Java]. I want to determine whether there is a "world" element in it. If there is, add a "javaee" element. Please write code to achieve it. 

code show as below:

// 创建集合对象
List<String> list = new ArrayList<String>();

// 添加元素
list.add("hello");
list.add("world");
list.add("Java");

// 遍历集合
// 使用迭代器遍历
Iterator<String> it = list.iterator();
while (it.hasNext()) {
	String str = it.next();
	if (str.equals("world")) {
		list.add("javaee");
	}
}

System.out.println("list:" + list);

The operation result reports an exception ConcurrentModificationException, as shown in the following figure:

ConcurrentModificationException: This exception is thrown when the method detects concurrent modification of the object, but such modification is not allowed. 

The reason for the concurrent modification exception: The iterator is dependent on the collection. After the judgment is successful, a new element is added to the collection, but the iterator does not know about it, so an exception is reported. This exception is called a concurrent modification exception. In fact, this problem describes: when the iterator traverses the elements, the elements cannot be modified through the collection.

The solution to concurrent modification exception:

  • Method 1: The iterator traverses the elements, and the iterator modifies the elements
// 方式一:迭代器遍历元素,迭代器修改元素
// 而Iterator迭代器却没有添加功能,所以我们使用其子接口ListIterator
ListIterator<String> lit = list.listIterator();
while (lit.hasNext()) {
	String str = lit.next();
	if (str.equals("world")) {
		lit.add("javaee");
	}
}
  • Method 2: The collection traverses the elements, and the collection modifies the elements (that is, the ordinary for loop)
// 方式二:集合遍历元素,集合修改元素
for (int i = 0; i < list.size(); i++) {
	String str = list.get(i);
	if (str.equals("world")) {
		list.add("javaee");
	}
}

The complete code is as follows:

package com.hw.list;

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

/**
 * 需求:有一个集合[Hello, World, Java],想判断里面有没有"world"这个元素,如果有,就添加一个"javaee"元素,请写代码实现。
 * 
 * ConcurrentModificationException:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。 
 * 
 * @author HW
 * 
 */
public class ConcurrentModificationExceptionDemo {
	public static void main(String[] args) {
		// 创建集合对象
		List<String> list = new ArrayList<String>();

		// 添加元素
		list.add("hello");
		list.add("world");
		list.add("Java");

		// 遍历集合
		// 使用迭代器遍历
		/*Iterator<String> it = list.iterator();
		while (it.hasNext()) {
			String str = it.next();
			if (str.equals("world")) {
				list.add("javaee");
			}
		}*/
		

		// 方式一:迭代器遍历元素,迭代器修改元素
		// 而Iterator迭代器却没有添加功能,所以我们使用其子接口ListIterator
		/*ListIterator<String> lit = list.listIterator();
		while (lit.hasNext()) {
			String str = lit.next();
			if (str.equals("world")) {
				lit.add("javaee");
			}
		}*/

		// 方式二:集合遍历元素,集合修改元素
		for (int i = 0; i < list.size(); i++) {
			String str = list.get(i);
			if (str.equals("world")) {
				list.add("javaee");
			}
		}

		System.out.println("list:" + list);
	}
}

4. Unique traversal function of List collection

  • Use the size() method in combination with the get() method
// 创建集合对象
List<String> list = new ArrayList<String>();

// 添加元素
list.add("Jmeter");
list.add("Selenium");
list.add("AirTest");
list.add("Python");
list.add("Fiddler");
		
// 遍历集合
// List集合的特有遍历功能(普通for循环遍历集合)
for (int i = 0; i < list.size(); i++) {
	System.out.println(list.get(i));
}

5. The characteristics of the three subcategories of List

ArrayList

  • The underlying data structure is an array, fast query, slow addition and deletion
  • Thread is not safe and efficient

Vector

  • The underlying data structure is an array, fast query, slow addition and deletion
  • Thread safe, low efficiency

LinkedList

  • The underlying data structure is a linked list, which is slow to query and fast to add and delete
  • Thread is not safe and efficient

6.ArrayList case

6.1 Store string and traverse

// 创建集合对象
ArrayList<String> list = new ArrayList<String>();

// 添加元素
list.add("Jmeter");
list.add("Selenium");
list.add("AirTest");
list.add("Python");
list.add("Fiddler");
		
// 遍历集合
// 方式一:普通for循环遍历集合
for (int i = 0; i < list.size(); i++) {
	System.out.println(list.get(i));
}
		
System.out.println("==========");
		
// 方式二:迭代器遍历集合
// 通过集合对象获取迭代器对象
Iterator<String> it = list.iterator();
while (it.hasNext()) {
	System.out.println(it.next());
}

6.2 Store custom objects and traverse

  • Student(name, age)
// 创建集合对象
ArrayList<Student> list = new ArrayList<Student>();

// 创建学生对象
Student s1 = new Student("西施", 18);
Student s2 = new Student("貂蝉", 16);
Student s3 = new Student("昭君", 20);
Student s4 = new Student("杨贵妃", 22);

// 把学生对象添加到集合中
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);

// 遍历集合
// 方式一:通过迭代器对象遍历集合
Iterator<Student> it = list.iterator();
while (it.hasNext()) {
	Student stu = it.next();
	System.out.println(stu.getName() + "---" + stu.getAge());
}

System.out.println("==========");

// 方式二:普通for循环遍历集合
for (int i = 0; i < list.size(); i++) {
	Student stu = list.get(i);
	System.out.println(stu.getName() + "---" + stu.getAge());
}

7. The unique functions of Vector

7.1 Add function

  • public void addElement(Object obj): add element

7.2 Get function

  • public Object elementAt(int index): Get the element at the specified index position
  • public Enumeration elements()
    • boolean hasMoreElements(): Determine whether there is the next element
    • Object nextElement(): Get the element

For the specific usage of the above functions, refer to the following code:

package com.hw.list;

import java.util.Enumeration;
import java.util.Vector;

/**
 * 添加功能 
 * 		public void addElement(Object obj)
 * 
 * 获取功能
 * 		public Object elementAt(int index) 
 * 		public Enumeration elements()
 * 			boolean hasMoreElements():判断是否有下一个元素
 * 			Object nextElement():获取元素
 * @author HW
 *
 */
public class VectorDemo {
	public static void main(String[] args) {
		// 创建集合对象
		Vector<String> vector = new Vector<String>();
		
		// 添加元素
		vector.addElement("Fiddler");
		vector.addElement("AirTest");
		vector.addElement("Selenium");
		
		System.out.println("vector集合:" + vector);
		
		// 获取指定位置的元素
		System.out.println("elementAt(1):" + vector.elementAt(1));

		// 通过集合对象获取枚举对象
		Enumeration<String> enu = vector.elements();
		// 判断是否有下一个元素
		while (enu.hasMoreElements()) {
			// 获取元素
			System.out.println(enu.nextElement());
		}
	}
}

8. Unique functions of LinkedList

8.1 Add function

  • public void addFirst(Object e): Insert an element at the beginning of the collection
  • public void addLast(Object e): Insert an element at the end of the collection

8.2 Get function

  • public Object getFirst(): Get the first element of the collection
  • public Obejct getLast(): Get the last element of the collection

8.3 Delete function

  • public Object removeFirst(): remove the first element of the collection
  • public Object removeLast(): remove the last element of the collection
// 创建集合对象
LinkedList<String> list = new LinkedList<String>();
		
// 添加元素
list.add("Selenium");
list.add("Jmeter");
list.add("Fiddler");
		
System.out.println("LinkedList集合:" + list);
		
System.out.println("==========在list集合的开头和结尾插入元素==========");
		
// 在list集合的开头插入元素
list.addFirst("AirTest");
// 在list集合的结尾插入元素
list.addLast("Java");
System.out.println("" + list);

System.out.println("返回list集合的第一个元素:" + list.getFirst());
System.out.println("返回list集合的最后一个元素:" + list.getLast());
		
System.out.println("移除list集合的第一个元素:" + list.removeFirst());
System.out.println("移除list集合的最后一个元素:" + list.removeLast());
		
System.out.println("最终元素:" + list);

The results of the operation are as follows:

LinkedList集合:[Selenium, Jmeter, Fiddler]
==========在list集合的开头和结尾插入元素==========
[AirTest, Selenium, Jmeter, Fiddler, Java]
返回list集合的第一个元素:AirTest
返回list集合的最后一个元素:Java
移除list集合的第一个元素:AirTest
移除list集合的最后一个元素:Java
最终元素:[Selenium, Jmeter, Fiddler]

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/105455810