Collection and List

Set interface and generics

Collection system interface

Arrays are not dynamic. Once an array is created, its capacity is fixed and cannot be modified. In order to add new elements, you need to create an array with a larger capacity, and copy the data to the new array. Example of new element in array

package day19;
import java.util.Arrays;
public class Day1901 {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
// arr[5] = 5;//java.lang.ArrayIndexOutOfBoundsException
int[] arr1 = Arrays.copyOf(arr, 6);
arr1[5] = 5;
System.out.println(arr1.length);//6
}
}

The collection is dynamic, and the collection allows dynamic addition and deletion of elements. When the number of elements exceeds the capacity of the collection, the collection will automatically expand.
There are a series of collections in java, which have their own purposes.
Insert picture description here

Collection interface

The Collection interface is the topmost interface in the Collection system. A Collection represents a group of objects, these objects are called elements.
The collection can only store objects, not basic data types, and can use packaging classes. The Collection interface defines a common
method that all collections must implement . Some types of collections allow duplicate elements, and some do not. Some types of collections are ordered, some are not. Java does not provide
specific implementation classes of the Collection interface, but provides specific implementation classes of its subinterfaces such as Set and List.
Collection interface API where E represents the type of elements in the collection

interface Collection<E> extends Iterable<E>
{
boolean add(E paramE);//添加一个元素
boolean remove(Object paramObject);//删除一个元素
int size();//获取集合中元素的数量
boolean isEmpty();//判断集合是否为空
void clear();//清空集合中的元素
boolean contains(Object paramObject);//判断集合中是否包含一个元素
Iterator<E> iterator();//获取此集合的一个迭代器,通过迭代器可以遍历集合中的元素
//还有很多方法
}

Use of Collection interface

package day19;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
public class Day1902 {
public static void main(String[] args) {
// 使用泛型参数String,表示这个集合中可以存放String类型的元素List接口
Collection<String> c = new HashSet<String>();
// 获取集合中元素的数量
System.out.println(c.size());
// 判断集合是否为空
System.out.println(c.isEmpty());
// 向集合中加入一个元素
c.add("张三");
// 获取集合中元素的数量
System.out.println(c.size());
// 判断集合是否为空
System.out.println(c.isEmpty());
c.add("李四");
c.add("王五");
c.add("马六");
System.out.println(c.size());// 4
// 判断集合中是否包含指定的元素
// contains方法会对集合中的每个元素依次调用equals方法来和contains方法的参数进行比较
// contains方法依赖于元素实现了equals方法
System.out.println(c.contains("李四"));// true
// 从集合中删除指定的对象
// remove方法会对集合中的每个元素依次调用equals方法来和remove方法的参数进行比较
// remove方法依赖于元素实现了equals方法
c.remove("李四");
// 由于Collection集合不记录元素的索引位置,必须使用迭代器来遍历集合
// 获取集合c的迭代器i
Iterator<String> i = c.iterator();
// hashNext方法用于判断迭代器中是否还有下一个元素
while (i.hasNext()) {
// next方法用于获取迭代器中的下一个元素
System.out.println(i.next());
} /
/ 所有的集合都有一个迭代器
// foreach可以应用于实现了Iterable接口的集合
// Collection接口继承于Iterable接口,因此Collection所有的子集合都可以获取迭代器
// foreach内部就是使用迭代器
for (String str : c) {
System.out.println(str);
}
}
}

List interface
Collection c = new HashSet();
// Get the number of elements in the collection
System.out.println(c.size());
// Determine whether the collection is empty
System.out.println(c.isEmpty()) ;
// Add an element to the collection
c.add("Zhang San");
// Get the number of elements in the collection
System.out.println(c.size());
// Determine whether the collection is empty
System.out .println(c.isEmpty());
c.add("李四");
c.add("王五");
c.add("马六");
System.out.println(c.size( )); // 4
// Determine whether the set contains the specified element
// The contains method will call the equals method for each element in the set in turn to compare the parameters of the contains method.
// The contains method depends on the element to implement equals Method
System.out.println(c.contains("Li Si"));// true
// Remove the specified object from the collection
// The remove method will call the equals method and the remove method for each element in the collection in turn The parameters are compared
// The remove method depends on the element to implement the equals method
c.remove("李四");
// Since the Collection collection does not record the index position of the element, an iterator must be used to traverse the collection
// Get the iterator of the collection c i
Iterator i = c.iterator();
// hashNext The method is used to determine whether there is the next element in the iterator
while (i.hasNext()) { // The next method is used to get the next element in the iterator System.out.println(i.next()); } // All collections have an iterator // foreach can be applied to a collection that implements the Iterable interface // Collection interface inherits from the Iterable interface, so all sub-collections of Collection can get iterators // foreach uses iterators inside for (String str: c) { System.out.println(str); } } }











List interface

The List interface inherits from the Collection interface, so it has all the methods of the Collection interface. The List interface is an ordered list, which preserves the order in which elements are added
and allows elements to be added to the specified position in the collection. The List interface is similar to an array, except that it can be dynamically extended. List interface schematic
diagram: Insert picture description here
When adding a new element, you can use the void add (E paramE) method to add the element to the end of the List collection. You can also use the void add(intparamInt, E paramE); method to add the element to the specified position. In this way, the original element at this position and subsequent elements will move down. You can also use the set and get methods to modify and get the element at the specified position. The methods of the List interface are not all listed.

interface List<E> extends Collection<E>
{
E get(int paramInt);//获取指定位置的元素
E set(int paramInt, E paramE);//替换指定位置的元素,返回旧元素
void add(int paramInt, E paramE);//方法将元素添加到指定的位置
E remove(int paramInt);//删除指定位置的元素
int indexOf(Object paramObject);//获取指定元素的位置
int lastIndexOf(Object paramObject);//获取指定原的位置,从后向前搜索
ListIterator<E> listIterator();//返回一个迭代器
List<E> subList(int paramInt1, int paramInt2);//返回子列表
}

The List interface has two implementation classes: ArrayList and LinkedList
. The use of
ArrayList : ArrayList implements the List interface, which saves the order of adding elements. The internal implementation of ArrayList is an array.

package day19;
import java.util.ArrayList;
import java.util.List;
public class Day1903 {
public static void main(String[] args) {
// 创建了一个ArrayList集合,可以保存Integer类型的对象
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(1);//自动装箱
list.add(3);
//向索引处1加入元素4
//原来所以处1的元素和后续的元素都会往后移动
list.add(1, 4);
//获取元素1的索引
System.out.println(list.indexOf(1));
//将索引处1的元素替换为5,此方法将返回旧元素
System.out.println(list.set(1, 5));
//将索引处1的元素删除,此方法将返回旧元素,后续的元素将会向前移动
list.remove(1);
//删除指定元素
list.remove(Integer.valueOf(2));
System.out.println("******************************");
//List集合保留插入元素的顺序,进行迭代时是按照插入元素的顺序
for (Integer i : list) {
System.out.println(i);
} S
ystem.out.println("******************************");
//由于List集合中的元素带有索引,因此可以使用for循环来遍历
for (int i = 0; i < list.size(); i++) {
//get方法用于获取指定索引处的元素
System.out.println(list.get(i));
}
}
}

ArrayList can save repeated elements
package day19;
import java.util.ArrayList;
import java.util.List;
public class Day1904 { public static void main(String[] args) { //List can save repeated elements List list = new ArrayList( ); list.add("张三"); list.add("张三"); list.add("张三"); System.out.println(list.size());//3 } } The Sort Collections.sort() method of List can sort List, provided that the elements in List implement the Comparable interface









package day19;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Day1905 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
for (String str : list) {
System.out.print(str + " ");
} 
System.out.println();
//String类的比较方式是按照ascii码表来比
Collections.sort(list);
for (String str : list) {
System.out.print(str + " ");
} 
System.out.println();
}
}
package day19;
public class Student implements Comparable<Student> {
private int sno;
private String name;
private int score;
public Student(int sno, String name, int score) {
super();
this.sno = sno;
this.name = name;
this.score = score;
} 
public int getSno() {
return sno;
} 
public void setSno(int sno) {
this.sno = sno;
}
 public String getName() {
return name;
}
 public void setName(String name) {
this.name = name;


 }
    public int getScore() {
    return score;
    }
     public void setScore(int score) {
    this.score = score;
    } @
    Override
    public int compareTo(Student o) {
    //分数高的排在前面,分数低的排在后面
    return o.score - this.score;
    }
    }

Sort using comparator

package day19;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}public String getName() {
return name;
} 
public void setName(String name) {
this.name = name;
} 
public int getAge() {
return age;
} 
public void setAge(int age) {
this.age = age;
}
}

package day19;
import java.util.Comparator;
public class PersonCompartor implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
//按照年龄从小到大排
return o1.getAge() - o2.getAge();
}
}
package day19;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Day1908 {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("张三", 20));
list.add(new Person("李四", 18));
list.add(new Person("王五", 19));
//使用比较器进行排序,这样List中的元素就不必实现Comparable接口
Collections.sort(list, new PersonCompartor());
for (Person p : list) {
System.out.print(p.getName() + " ");
} 
System.out.println();
}

Convert List to array

package day19;
import java.util.ArrayList;
import java.util.List;
public class Day1909 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
String[] arr = new String[list.size()];
// 将list转换为数组
list.toArray(arr);
for (String str : arr) {
System.out.println(str);
}
}
}

Convert array to List

package day19;
import java.util.Arrays;
import java.util.List;
public class Day1910 {
public static void main(String[] args) {
String[] values = {"a", "b", "c", "d"};
//将数组转换为List
List<String> list = Arrays.asList(values);
for (String str : list) {
System.out.println(str);
}
}
}

LinkedList
LinkedList implements the List interface. LinkedList and ArrayList have the same methods, but the internal implementation is different. ArrayList uses an array internally, and LinkedList uses a linked list internally. An array is a continuous memory unit, and a linked list is not a continuous memory unit. The linked
list associates the elements in the linked list by reference . LinkedList diagram:

Insert picture description here

import java.util.LinkedList;
import java.util.List;
public class Day1911 {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
for (String str : list) {
System.out.print(str + " ");
} 
System.out.println();
}
}

LinkedList and ArrayList are slower than adding and deleting elements from ArrayList because the entire array needs to be copied. The LinkedList adds and deletes elements quickly, because only the reference needs to be modified. However, this is theoretical, not in practice. But the query speed of ArrayList is significantly faster LinkedList.

Guess you like

Origin blog.csdn.net/qq_45092505/article/details/100849646