Java list接口及实例

Java list接口及实例

Java中的List接口提供了一种存储有序集合的方法。它是Collection的一个子接口。它是一个对象的有序集合,其中可以存储重复的值。由于List保留了插入顺序,所以它允许元素的位置访问和插入。

List接口在java.util包中找到,它继承了Collection接口。它是ListIterator接口的一个工厂。通过ListIterator,我们可以向前和向后迭代列表。List接口的实现类是ArrayList、LinkedList、Stack和Vector。ArrayList和LinkedList在Java编程中被广泛使用。Vector类从Java 5开始被弃用。

Java中的List接口及实例

声明: List接口被声明为。

public interface List<E> extends Collection<E> ; 
Java

让我们阐述一下在List类中创建对象或实例的问题。 因为 List 是一个接口,所以不能创建List类型的对象。我们总是需要一个实现 List 的类来创建一个对象。而且,在Java 1.5中引入泛型之后,我们可以限制可以存储在List中的对象的类型。就像其他几个由用户定义的 “类 “实现的用户定义的 “接口 “一样, List 也是一个 “接口”,由 java.util 包中预先定义的 ArrayList 类实现。

语法: 这种类型的安全列表可以定义为。

List<Obj> list = new ArrayList<Obj> (); 
Java

注: Obj是要存储在List中的对象的类型。

例子

// Java program to Demonstrate List Interface
  
// Importing all utility classes
import java.util.*;
  
// Main class
// ListDemo class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an object of List interface
         // implemented by the ArrayList class
        List<Integer> l1 = new ArrayList<Integer>();
  
        // Adding elements to object of List interface
        // Custom inputs
  
        l1.add(0, 1);
        l1.add(1, 2);
  
        // Print the elements inside the object
        System.out.println(l1);
  
        // Now creating another object of the List 
        // interface implemented ArrayList class
        // Declaring object of integer type
        List<Integer> l2 = new ArrayList<Integer>();
  
        // Again adding elements to object of List interface
        // Custom inputs
        l2.add(1);
        l2.add(2);
        l2.add(3);
  
        // Will add list l2 from 1 index
        l1.addAll(1, l2);
  
        System.out.println(l1);
  
        // Removes element from index 1
        l1.remove(1);
  
        // Printing the updated List 1
        System.out.println(l1);
  
        // Prints element at index 3 in list 1
        // using get() method
        System.out.println(l1.get(3));
  
        // Replace 0th element with 5
        // in List 1
        l1.set(0, 5);
  
        // Again printing the updated List 1
        System.out.println(l1);
    }
}
Java

输出

[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
Java

现在让我们使用List Interface来执行各种操作,以便更好地理解这些操作。我们将讨论下面列出的操作,并在以后通过简洁的java代码来实现。

List接口中的操作

由于List是一个接口,它只能与实现该接口的类一起使用。现在,让我们看看如何在List上执行一些常用的操作。

  • 操作1: 使用add()方法向List类添加元素
  • 操作2: 使用set()方法更新List类中的元素
  • 操作3: 使用remove()方法删除元素

现在让我们单独讨论这些操作,并在代码中实现这些操作,以便更好地掌握它。

操作1: 使用 add()方法 向List类添加元素

为了向列表中添加一个元素,我们可以使用add()方法。这个方法是重载的,可以根据不同的参数执行多种操作。

参数: 它需要2个参数,即。

  • add(Object): 这个方法用来在列表的最后添加一个元素。
  • add( int index, Object): 这个方法用来在List的特定索引处添加一个元素。

例子

// Java Program to Add Elements to a List
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of List interface, 
        // implemented by ArrayList class
        List<String> al = new ArrayList<>();
  
        // Adding elements to object of List interface
        // Custom elements
        al.add("Geeks");
        al.add("Geeks");
        al.add(1, "For");
  
        // Print all the elements inside the
        // List interface object
        System.out.println(al);
    }
}
Java

输出

[Geeks, For, Geeks]
Java

操作2: 更新元素

在添加完元素后,如果我们想改变元素,可以用 set() 方法 来完成 。 由于List是有索引的,我们希望改变的元素是通过元素的索引来引用的。因此,这个方法需要一个索引和需要在该索引处插入的更新元素。

例子

// Java Program to Update Elements in a List
  
// Importing utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of List interface
        List<String> al = new ArrayList<>();
  
        // Adding elements to object of List class
        al.add("Geeks");
        al.add("Geeks");
        al.add(1, "Geeks");
  
        // Display theinitial elements in List
        System.out.println("Initial ArrayList " + al);
  
        // Setting (updating) element at 1st index
        // using set() method
        al.set(1, "For");
  
        // Print and display the updated List
        System.out.println("Updated ArrayList " + al);
    }
}
Java

输出

Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
Java

操作3: 删除元素

为了从一个列表中删除一个元素,我们可以使用 remove()方法 这个方法被重载,可以根据不同的参数执行多种操作。它们是

参数

  • remove(Object): 这个方法被用来简单地从列表中删除一个对象。如果有多个这样的对象,那么第一个出现的对象将被删除。
  • remove(int index): 由于List是有索引的,这个方法需要一个整数值,它可以简单地删除List中存在于该特定索引的元素。在删除元素后,所有的元素都被移到左边以填补空间,对象的索引被更新。

例子

// Java Program to Remove Elements from a List
  
// Importing List and ArrayList classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Creating List class object
        List<String> al = new ArrayList<>();
  
        // Adding elements to the object
        // Custom inputs
        al.add("Geeks");
        al.add("Geeks");
  
        // Adding For at 1st indexes
        al.add(1, "For");
  
        // Print the initialArrayList
        System.out.println("Initial ArrayList " + al);
  
        // Now remove element from the above list
        // present at 1st index
        al.remove(1);
  
        // Print the List after removal of element
        System.out.println("After the Index Removal " + al);
  
        // Now remove the current object from the updated
        // List
        al.remove("Geeks");
  
        // Finally print the updated List now
        System.out.println("After the Object Removal "
                           + al);
    }
}
Java

输出

Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
Java

迭代列表

到目前为止,我们的输入规模非常小,而且我们正在对每个实体进行手动操作。现在让我们讨论一下各种方法,我们可以通过这些方法对列表进行迭代,让它们在更大的样本集上工作。

方法: 有多种方法可以对列表进行迭代。最著名的方法是通过使用基本的for循环和get()方法来获取特定索引的元素,以及使用高级for循环。

例子

// Java program to Iterate the Elements
// in an ArrayList
  
// Importing java utility classes
import java.util.*;
  
// Main class
public class GFG {
  
    // main driver method
    public static void main(String args[])
    {
        // Creating an empty Arraylist of string type
        List<String> al = new ArrayList<>();
  
        // Adding elements to above object of ArrayList
        al.add("Geeks");
        al.add("Geeks");
  
        // Adding element at specified position
        // inside list object
        al.add(1, "For");
  
        // Using  for loop for iteration
        for (int i = 0; i < al.size(); i++) {
  
            // Using get() method to
            // access particular element
            System.out.print(al.get(i) + " ");
        }
  
        // New line for better readability
        System.out.println();
  
        // Using for-each loop for iteration
        for (String str : al)
  
            // Printing all the elements
            // which was inside object
            System.out.print(str + " ");
    }
}
Java

输出

Geeks For Geeks 
Geeks For Geeks 
Java

列表接口的方法

由于不同类型的列表背后的主要概念是相同的,所以列表接口包含以下方法。

方法 描述
add(int index, element) 这个方法用于在列表中的特定索引处添加一个元素。当一个参数被传递时,它只是在列表的末尾添加元素。
addAll(int index, Collection collection) 这个方法用来添加给定集合中的所有元素到列表中。当一个参数被传递时,它在列表的末尾添加给定集合的所有元素。
size() 该方法用于返回列表的大小。
clear() 这个方法用来删除列表中的所有元素。然而,创建的列表的引用仍然被保存。
remove(int index) 这个方法从指定的索引中删除一个元素。它将随后的元素(如果有的话)向左移动并将它们的索引减少1。
remove(element) 这个方法用来删除列表中第一次出现的元素。
get(int index) 该方法返回指定索引处的元素。
set(int index, element) 这个方法用新的元素替换给定索引上的元素。这个函数返回刚刚被新元素替换的元素。
indexOf(element) 该方法返回给定元素的第一次出现,如果该元素在列表中不存在,则返回 -1
lastIndexOf(element) 该方法返回给定元素的最后一次出现,如果该元素在列表中不存在,则返回 -1
equals(element) 该方法用于比较给定元素与列表中的元素是否相等。
hashCode() 此方法用于返回给定列表的哈希码值。
isEmpty() 此方法用于检查列表是否为空。如果列表是空的,它返回 true,否则返回 false。
contains(element) 该方法用于检查列表是否包含给定的元素。如果列表包含该元素,它返回 true。
containsAll(Collection collection) 该方法用于检查列表是否包含所有的元素集合。
sort(Comparator comp) 这个方法用于在给定的比较器的基础上对列表中的元素进行排序。

Java List vs Set

List接口和Set接口都继承了Collection接口。然而,它们之间存在着一些区别。

列表 集合
List是一个有序的序列。 Set是一个无序的序列。
列表允许重复的元素 Set不允许重复的元素。
可以通过其位置访问元素。 不允许对元素进行位置访问。
可以存储多个空元素。 空元素只能存储一次。
列表的实现有ArrayList, LinkedList, Vector, Stack 集合的实现是HashSet, LinkedHashSet.

与List接口相关的类

现在让我们来讨论一下实现List接口的类,首先请参考下面的图示,以便更好地理解List接口的含义。它如下所示。

Java中的List接口及实例

AbstractList、CopyOnWriteArrayList和AbstractSequentialList都是实现List接口的类。每个提到的类都实现了单独的功能。它们是如下的。

  1. AbstractList: 该类用于实现一个不可修改的列表,为此只需要扩展这个AbstractList类,并只实现get()和size()方法。
  2. CopyOnWriteArrayList: 该类实现了列表接口。它是ArrayList的增强版,其中所有的修改(添加、设置、删除等)都是通过对列表进行新的复制来实现的。
  3. AbstractSequentialList: 该类实现了Collection接口和AbstractCollection类。这个类被用来实现一个不可修改的列表,为此只需要扩展这个AbstractList类,并只实现get() 和size()方法。

我们将以这种方式进行。

  • ArrayList
  • Vector
  • Stack
  • LinkedList

让我们按顺序讨论它们,并实现它们,以弄清具有List接口的类的工作。

类1:ArrayList

在集合框架中实现的 ArrayList 类为我们提供了Java中的动态数组。尽管它可能比标准数组慢,但在需要对数组进行大量操作的程序中是很有帮助的。让我们看看如何使用这个类来创建一个列表对象。

例子

// Java program to demonstrate the
// creation of list object using the
// ArrayList class
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Size of ArrayList
        int n = 5;
  
        // Declaring the List with initial size n
        List<Integer> arrli
            = new ArrayList<Integer>(n);
  
        // Appending the new elements
        // at the end of the list
        for (int i = 1; i <= n; i++)
            arrli.add(i);
  
        // Printing elements
        System.out.println(arrli);
  
        // Remove element at index 3
        arrli.remove(3);
  
        // Displaying the list after deletion
        System.out.println(arrli);
  
        // Printing elements one by one
        for (int i = 0; i < arrli.size(); i++)
            System.out.print(arrli.get(i) + " ");
    }
}
Java

输出

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 
Java

类2:向量

Vector是一个在集合框架中实现的类,它实现了对象的可增长数组。Vector实现了一个动态数组,这意味着它可以根据需要增长或缩小。像一个数组一样,它包含的组件可以使用一个整数索引进行访问。矢量基本上属于遗留类,但现在它与集合完全兼容。让我们看看如何使用这个类来创建一个列表对象。

例子

// Java program to demonstrate the
// creation of list object using the
// Vector class
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Size of the vector
        int n = 5;
  
        // Declaring the List with initial size n
        List<Integer> v = new Vector<Integer>(n);
  
        // Appending the new elements
        // at the end of the list
        for (int i = 1; i <= n; i++)
            v.add(i);
  
        // Printing elements
        System.out.println(v);
  
        // Remove element at index 3
        v.remove(3);
  
        // Displaying the list after deletion
        System.out.println(v);
  
        // Printing elements one by one
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}
Java

输出

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 
Java

类3:Stack

Stack是一个在集合框架中实现的类,它扩展了向量类的模型并实现了Stack数据结构。该类是基于后进先出的基本原则。除了基本的push和pop操作外,该类还提供了empty、search和peek三种功能。让我们看看如何使用这个类来创建一个列表对象。

例子

// Java program to demonstrate the
// creation of list object using the
// Stack class
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Size of the stack
        int n = 5;
  
        // Declaring the List
        List<Integer> s = new Stack<Integer>();
  
        // Appending the new elements
        // at the end of the list
        for (int i = 1; i <= n; i++)
            s.add(i);
  
        // Printing elements
        System.out.println(s);
  
        // Remove element at index 3
        s.remove(3);
  
        // Displaying the list after deletion
        System.out.println(s);
  
        // Printing elements one by one
        for (int i = 0; i < s.size(); i++)
            System.out.print(s.get(i) + " ");
    }
}
Java

输出

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 
Java

类4:LinkedList

LinkedList是一个在集合框架中实现的类,它内在地实现了链接列表数据结构。它是一个线性的数据结构,其中的元素不是存储在连续的位置,每个元素都是一个独立的对象,有数据部分和地址部分。这些元素使用指针和地址进行链接。每个元素被称为一个节点。由于其动态性和易于插入和删除,它们比数组更受欢迎。让我们看看如何使用这个类来创建一个列表对象。

例子

// Java program to demonstrate the
// creation of list object using the
// LinkedList class
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Size of the LinkedList
        int n = 5;
  
        // Declaring the List with initial size n
        List<Integer> ll = new LinkedList<Integer>();
  
        // Appending the new elements
        // at the end of the list
        for (int i = 1; i <= n; i++)
            ll.add(i);
  
        // Printing elements
        System.out.println(ll);
  
        // Remove element at index 3
        ll.remove(3);
  
        // Displaying the list after deletion
        System.out.println(ll);
  
        // Printing elements one by one
        for (int i = 0; i < ll.size(); i++)
            System.out.print(ll.get(i) + " ");
    }
}
Java

输出

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册