List 接口允许存储有序集合。它是 Collection 的子接口。它是一个有序的对象集合,其中允许存储重复的值。 List 保留插入顺序,它允许元素的位置访问和插入。
宣言:
public abstract interface List extends Collection
Java.util 包中的set 接口和 extends Collection 接口是一个无序的对象集合,其中不能存储重复值。它是一个实现数学集的接口。该接口包含继承自 Collection 接口的方法,并添加了限制插入重复元素的功能。
声明: Set 接口声明为:
public interface Set extends Collection
例子:
Input : Add Elements = [1, 2, 3, 1]
Output: Set = [1, 2, 3]
List = [1, 2, 3, 1]
Input : Add Elements = [a, b, d, b]
Output: Set = [a, b, d]
List = [a, b, d, b]
下面是 Set 和 List 的说明:
Java
// Implementation of List and Set in Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// List declaration
List l = new ArrayList<>();
l.add(5);
l.add(6);
l.add(3);
l.add(5);
l.add(4);
// Set declaration
Set s = new HashSet<>();
s.add(5);
s.add(6);
s.add(3);
s.add(5);
s.add(4);
// printing list
System.out.println("List = " + l);
// printing Set
System.out.println("Set = " + s);
}
}
输出
List = [5, 6, 3, 5, 4]
Set = [3, 4, 5, 6]
列表和集合的区别:
List | Set |
---|---|
1. The List is an ordered sequence. | 1. The Set is an unordered sequence. |
2. List allows duplicate elements | 2. Set doesn’t allow duplicate elements. |
3. Elements by their position can be accessed. | 3. Position access to elements is not allowed. |
4. Multiple null elements can be stored. | 4. Null element can store only once. |
5. List implementations are ArrayList, LinkedList, Vector, Stack | 5. Set implementations are HashSet, LinkedHashSet. |