List Interface trong Java

1. List Interface

List Interface trong Java kế thừa Collection và nó cung cấp các phương thức để thao tác với các phần tử trong danh sách.

Interface java.util.List được định nghĩa như sau:

public interface List<E> extends Collection<E>

Các phương thức của List interface

Phương thcMô tả
void add(int index, Object obj)Chèn obj vào trong List đang gọi tại index đã cho. Bất kỳ phần tử nào đã tồn tại trước tại hoặc trên điểm chèn bị bỏ qua. Vì thế, không có phần tử nào bị ghi đè.
boolean addAll(int index, Collection c)Chèn tất cả phần tử của c vào trong List đang gọi tại chỉ mục đã cho. Bất kỳ phần tử nào đã tồn tại trước tại hoặc trên điểm chèn bị bỏ qua. Vì thế, không có phần tử nào bị ghi đè. Trả về true nếu List đang gọi thay đổi và nếu không trả về false.
object get(int index)Trả về đối tượng được lưu giữ tại index đã cho bên trong Collection đang gọi.
int indexOf(Object obj)Trả về index của sự xuất hiện đầu tiên của obj trong List đang gọi. Nếu obj không là một phần tử trong list, -1 được trả về.
int lastIndexOf(Object obj)Trả về index của sự xuất hiện đầu tiên của obj trong List đang gọi. Nếu obj không là một phần tử trong list, -1 được trả về
ListIterator listIterator()Sử dụng để trả về một Iterator mà bắt đầu từ phần tử đầu tiên của list.
ListIterator listIterator(int index)Sử dụng để trả về một Iterator mà phần tử bắt đầu từ chỉ số index chỉ định.
object remove(int index)Gỡ bỏ phần tử tại index từ List đang gọi và trả về phần tử bị xóa đó. List kết quả được compact lại. Đó là, các chỉ mục của dãy phần tử phụ bị lượng giảm đi 1.
object set(int index, Object obj)Gán obj tới vị trí được xác định bởi index bên trong List đang gọi.
List subList(int start, int end)Trả về một list mà bao gồm các phần tử từ start tới end-1 trong List đang gọi. Các phần tử trong list trả về cũng được tham chiếu bởi đối tượng đang gọi.

Ví dụ:

import java.util.ArrayList;
import java.util.List;
 
public class ListExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // Add element to list
            list.add("0" + i);
        }
 
        // Show list through for-each
        for (String item : list) {
            System.out.print(item + " ");
        }
    }
}
&#91;/code&#93;
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>Kết quả thực thi chương trình trên:</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->

01 02 03 04 05

2. Iterator Interface

Iterator là một Interface, nó  cung cấp một số các phương thức để duyệt qua các phần tử của bất kỳ tập hợp nào. Mỗi interface Collection trong Java đều chứa một phương thức iterator để trả về một thực thể của interface Iterator.

Iterator có khả năng xoá những phần từ tập hợp trong quá trình lặp. Sử dụng for hoặc for-each, bạn không thể xóa phần tử trong khi duyệt các phần tử.

Interface java.util.Iterator được định nghĩa như sau:

public interface Iterator<E>

Ví dụ không thể duyệt và xóa phần tử với for:

import java.util.ArrayList;
import java.util.List;
 
public class IteratorExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // Add element to list
            list.add("0" + i);
        }
 
        // traversing the list in the forward direction
        for (int i = 0; i < 5; i++) {
            list.remove(i);
        }
    }
}
&#91;/code&#93;
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>Thực thi chương trình trên, bạn sẽ gặp lỗi&nbsp;<strong>IndexOutOfBoundsException</strong>&nbsp;như sau:</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.remove(ArrayList.java:492)
    at com.maixuanviet.collection.arraylist.IteratorExample.main(IteratorExample.java:17)

Ví dụ không thể duyệt và xóa phần tử với for-each:

import java.util.ArrayList;
import java.util.List;
 
public class IteratorExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // Add element to list
            list.add("0" + i);
        }
 
        // traversing the list in the forward direction
        for (String item : list) {
            list.remove(item);
        }
    }
}
&#91;/code&#93;
<!-- /wp:shortcode -->

<!-- wp:paragraph -->
<p>Thực thi chương trình trên, bạn sẽ gặp lỗi&nbsp;<strong>ConcurrentModificationException</strong>&nbsp;như sau:</p>
<!-- /wp:paragraph -->

<!-- wp:shortcode -->

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at com.maixuanviet.collection.arraylist.IteratorExample.main(IteratorExample.java:19)

Ví dụ có thể sử dụng for duyệt từ phần tử cuối cùng về phần tử đầu tiên để xóa phần tử:

import java.util.ArrayList;
import java.util.List;
 
public class IteratorExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) { // Add element to list list.add("0" + i); } // traversing the list in the backward direction for (int i = 4; i >= 0; i--) {
            list.remove(i);
        }
        System.out.println("list.isEmpty() = " + list.isEmpty());
    }
}

Kết quả thực thi chương trình trên:

list.isEmpty() = true

Ví dụ sử dụng Iterator để duyệt và xóa phần tử trong khi duyệt:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class IteratorExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // Add element to list
            list.add("0" + i);
        }
 
        Iterator<String> iterator = list.iterator();
        System.out.println("Using Iterator: Only Traversing the list in the forward direction ");
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
            iterator.remove();
        }
        System.out.println();
        System.out.println("list.isEmpty() = " + list.isEmpty());
    }
}

Kết quả thực thi chương trình trên:

Using Iterator: Only Traversing the list in the forward direction 
01 02 03 04 05
list.isEmpty() = true

Như ví dụ trên, chúng ta có thể xóa phần tử trong khi duyệt qua collection.

3. ListIterator Interface

ListIterator là một interface kế thừa từ lớp Iterator, nó cung cấp phương thức để duyệt các phần tử của List trong java theo cả 2 chiều.

Interface java.util.ListIterator được định nghĩa như sau:

public interface ListIterator<E> extends Iterator<E>

Các phương thức của ListIterator interface

Phương thcMô tả
boolean hasNext()Trả về true nếu list interator có tồn tại phần tử kế tiếp phần tử hiện tại.
Object next()Trả về phần tử kế tiếp trong danh sách và vị trí con trỏ tăng lên 1.
boolean hasPrevious()Trả về true nếu list interator có tồn tại phần tử kế sau phần tử hiện tại.
Object previous()Trả về phần tử kế sau trong danh sách và vị trí con trỏ giảm đi 1

Ví dụ:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
 
public class ListIteratorExample {
    public static void main(String[] args) {
        // Create list with no parameter
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            // Add element to list
            list.add("0" + i);
        }
 
        Iterator<String> iterator = list.iterator();
        System.out.println("Using Iterator: Only Traversing the list in the forward direction ");
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
 
        System.out.println();
        ListIterator<String> itr = list.listIterator();
        System.out.println("Using ListIterator: Traversing the list in the forward direction ");
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
 
        System.out.println();
        System.out.println("Using ListIterator: Traversing the list in the reverse direction ");
        while (itr.hasPrevious()) {
            System.out.print(itr.previous() + " ");
        }
 
    }
}

Kết quả thực thi chương trình trên:

Using Iterator: Only Traversing the list in the forward direction 
01 02 03 04 05
Using ListIterator: Traversing the list in the forward direction 
01 02 03 04 05
Using ListIterator: Traversing the list in the reverse direction 
05 04 03 02 01

4. So sánh Iterator và ListIterator

IteratorListIterator
Iterator đưọc sử dụng để duyệt qua các interface Set và List.ListIterator chỉ đuợc sử dụng để duyệt qua List.
Iterator có thể duyệt qua các phần tử trong tập hợp chỉ theo một huớng.ListIterator có thể duyệt qua List tất cả các huớng (2 huớng).
Không thể thêm, thay thể phần tử khi sử dụng Iterator.ListIterator cài đặt interface Iterator và chứa thêm một số chức năng mới, như thêm mới một phần tử, thay thế phần từ, lấy chỉ mục (index) cho phần từ kế truớc hay sau nó, etc.

Related posts:

Java Program to Perform String Matching Using String Library
Create Java Applet to Simulate Any Sorting Technique
Introduction to Liquibase Rollback
How to Define a Spring Boot Filter?
New Features in Java 11
Converting Between Byte Arrays and Hexadecimal Strings in Java
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Service Registration with Eureka
Java Program to Implement Queue using Two Stacks
Injecting Prototype Beans into a Singleton Instance in Spring
Các nguyên lý thiết kế hướng đối tượng – SOLID
A Guide to Concurrent Queues in Java
Request Method Not Supported (405) in Spring
Overflow and Underflow in Java
Derived Query Methods in Spring Data JPA Repositories
Giới thiệu java.io.tmpdir
Java Program to Compute Determinant of a Matrix
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Spring Security Custom AuthenticationFailureHandler
Spring WebFlux Filters
Intro to Inversion of Control and Dependency Injection with Spring
Java – InputStream to Reader
Java – Generate Random String
Java Program to Implement Johnson’s Algorithm
Intro to the Jackson ObjectMapper
Hướng dẫn Java Design Pattern – State
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Updating your Password
The Spring @Controller and @RestController Annotations

2 Trackbacks / Pingbacks

  1. So sánh Array và ArrayList trong Java – Blog của VietMX
  2. Lớp Collections trong Java (Collections Utility Class) – Blog của VietMX

Comments are closed.