📜  用示例列出Java中的接口

📅  最后修改于: 2022-05-13 01:55:23.593000             🧑  作者: Mango

用示例列出Java中的接口

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

List 接口位于Java.util 包中,继承了 Collection 接口。它是 ListIterator 接口的工厂。通过 ListIterator,我们可以对列表进行正向和反向迭代。 List接口的实现类有ArrayList、LinkedList、Stack和Vector。 ArrayList 和 LinkedList 在Java编程中被广泛使用。自Java 5 起,Vector 类已被弃用。

List-and-ArrayList-in-Java-Collection-Framework

声明: List接口声明为:

public interface List extends Collection ; 

让我们详细说明在 List 类中创建对象或实例。由于List是一个接口,因此无法创建 list 类型的对象。我们总是需要一个实现这个List的类来创建一个对象。而且,在Java 1.5 中引入泛型之后,可以限制可以存储在 List 中的对象类型。就像其他几个由用户定义的“类”实现的用户定义的“接口”一样, List是一个“接口”,由ArrayList类实现,在Java.util包中预定义。

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

List list = new ArrayList (); 

例子:

Java
// 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 l1 = new ArrayList();
 
        // 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 l2 = new ArrayList();
 
        // 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
// 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 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
// 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 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
// 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 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
// 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 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
// 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 arrli
            = new ArrayList(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
// 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 v = new Vector(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
// 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 s = new Stack();
 
        // 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
// 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 ll = new LinkedList();
 
        // 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) + " ");
    }
}


输出
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]

现在让我们使用 List 接口执行各种操作,以更好地理解它们。我们将讨论下面列出的以下操作,稍后将讨论通过干净的Java代码实现。

List接口中的操作

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

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

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

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

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

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

  • add(Object):此方法用于在 List 的末尾添加一个元素。
  • add(int index, Object):该方法用于在List的特定索引处添加元素

例子:

Java

// 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 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);
    }
}
输出
[Geeks, For, Geeks]

操作 2:更新元素

添加元素后,如果我们想更改元素,可以使用 设置()方法。由于 List 是索引的,因此我们希望更改的元素由元素的索引引用。因此,此方法采用索引和需要在该索引处插入的更新元素。

例子:

Java

// 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 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);
    }
}
输出
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]

操作 3:移除元素

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

参数:

  • remove(Object):此方法用于简单地从列表中删除一个对象。如果有多个这样的对象,则删除第一次出现的对象。
  • remove(int index):由于 List 是索引的,因此此方法采用一个整数值,该值仅删除 List 中该特定索引处存在的元素。删除元素后,所有元素都向左移动以填充空间并更新对象的索引。

例子:

Java

// 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 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);
    }
}
输出
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]

迭代列表

到目前为止,我们的输入规模非常小,我们正在为每个实体手动操作。现在让我们讨论各种方法,通过这些方法我们可以遍历列表以使它们适用于更大的样本集。

方法:有多种方法可以遍历列表。最著名的方法是结合使用基本的 for 循环和 get() 方法来获取特定索引处的元素和高级的 for 循环。

例子:

Java

// 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 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 + " ");
    }
}
输出
Geeks For Geeks 
Geeks For Geeks 

List接口的方法

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

Method

Description

add(int index, element)This method is used to add an element at a particular index in the list. When a single parameter is passed, it simply adds the element at the end of the list.
addAll(int index, Collection collection)This method is used to add all the elements in the given collection to the list. When a single parameter is passed, it adds all the elements of the given collection at the end of the list.
size()This method is used to return the size of the list.
clear()This method is used to remove all the elements in the list. However, the reference of the list created is still stored.
remove(int index)This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
remove(element)This method is used to remove the first occurrence of the given element in the list.
get(int index)This method returns elements at the specified index.
set(int index, element)This method replaces elements at a given index with the new element. This function returns the element which was just replaced by a new element.
indexOf(element)This method returns the first occurrence of the given element or -1 if the element is not present in the list.
lastIndexOf(element)This method returns the last occurrence of the given element or -1 if the element is not present in the list.
equals(element)This method is used to compare the equality of the given element with the elements of the list.
hashCode()This method is used to return the hashcode value of the given list.
isEmpty()This method is used to check if the list is empty or not. It returns true if the list is empty, else false.
contains(element)This method is used to check if the list contains the given element or not. It returns true if the list contains the element.
containsAll(Collection collection)This method is used to check if the list contains all the collection of elements.
sort(Comparator comp)This method is used to sort the elements of the list on the basis of the given comparator.

Java列表与集合

List 接口和 Set 接口都继承了 Collection 接口。但是,它们之间存在一些差异。

ListSet
The List is an ordered sequence.The Set is an unordered sequence.
List allows duplicate elementsSet doesn’t allow duplicate elements.
Elements by their position can be accessed.Position access to elements is not allowed.
Multiple null elements can be stored.The null element can store only once.
List implementations are ArrayList, LinkedList, Vector, StackSet implementations are HashSet, LinkedHashSet.

与列表接口的类关联

现在让我们讨论实现 List 接口的类,首先参考下面的图示来更好地理解 List 接口。如下:

List-ArrayList-in-Java-In-Depth-Study

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

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

我们将以这种方式进行。

  • 数组列表
  • 向量
  • 链表

让我们按顺序讨论它们并实现它们以找出具有 List 接口的类的工作原理。

第 1 类:数组列表

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

例子:

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 arrli
            = new ArrayList(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) + " ");
    }
}
输出
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 

第 2 类:矢量

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

例子:

Java

// 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 v = new Vector(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) + " ");
    }
}
输出
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 

第 3 类:堆栈

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

例子:

Java

// 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 s = new Stack();
 
        // 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) + " ");
    }
}
输出
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 

第 4 类:链表

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

例子:

Java

// 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 ll = new LinkedList();
 
        // 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) + " ");
    }
}
输出
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5