Trong các bài viết trước, tôi đã giới thiệu với các bạn Array và ArrayList. Trong bài này, tôi sẽ so sánh sự khác nhau giữa Array và ArrayList.
| Array | ArrayList |
| Array có kích thước cố định. Không thể thay đổi kích thước nếu nó đã được tạo. | Kích thước của ArrayList có thể thay đổi được. Kích thước của nó tự tăng (50% kích thước hiện có) nếu thêm một phần tử vượt quá sức chứa (compacity) hiện có của nó. |
| Có thể lưu trữ dữ liệu kiểu nguyên thủy và đối tượng. | Chỉ có thể lưu trữ dữ liệu kiểu đối tượng (Object). Kể từ Java 5, kiểu nguyên thủy được tự động chuyển đổi trong các đối tượng được gọi là auto-boxing. Ví dụ: không thể khai báo ArrayList<int> |
| Sử dụng for hoặc for-each để duyệt qua các phần tử của mảng. | Tương tự như Array, có thể duyệt qua các phần tử bằng lệnh for hoặc for-each. Tuy nhiên, nó có thể duyệt qua Iterator hoặc ListIterator.Xem thêm bài viết ListIterator |
| Kích thước của Array có thể được kiểm tra bằng thuộc tính length. | Kích thước của ArrayList được kiểm tra bằng phương thức size(). |
| Không hỗ trợ kiểu Generic | Hỗ trợ kiểu Generic |
| Các phần tử được thêm vào danh sách bằng lệnh gán. | Các phần tử được thêm vào danh sách bằng phương thức add(). |
Ví dụ: Khởi tạo một mảng có 5 phần tử: bạn không thể thêm phần tử thứ 6 vào mảng hoặc thay đổi kích thước của nó.
int []arr = new int[5]; arr[5] = 6;
Khi thực thi chương trình trên, bạn sẽ gặp lỗi java.lang.ArrayIndexOutOfBoundsException.
Tuy nhiên, đối với ArrayList không bị giới hạn về số lượng phần tử. Khi vượt quá kích thước khởi tạo, nó tự động tăng lên 50% để lưu thêm phần tử mới.
import java.lang.reflect.Field;
import java.util.ArrayList;
public class ArrayExample {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<>(5);
list.add("Item01");
list.add("Item02");
list.add("Item03");
list.add("Item04");
list.add("Item05");
list.add("Item06");
System.out.format("Size: %d, Capacity: %d%n", list.size(), getCapacity(list));
}
public static int getCapacity(ArrayList<?> list) throws Exception {
Field dataField = ArrayList.class.getDeclaredField("elementData");
dataField.setAccessible(true);
return ((Object[]) dataField.get(list)).length;
}
}
Kết quả thực thi chương trình trên:
Size: 6, Capacity: 7
Trong chương trình trên:
- Ban đầu ArrayList khởi tạo sức chứa là 5 phần tử. Khi thêm phần tử thứ 6, do vượt quá sức chứa nên nó tăng 50% kích thước hiện có: 5 + (5/2) = 7.
- Do ArrayList không cung cấp phương thức để lấy sức chứa (compacity) hiện tại của nó, nên tôi sử dụng cơ chế Reflection để lấy giá trị compacity. Tôi sẽ giới thiệu với các bạn Refection trong Java sau khi kết thúc loạt bài viết về Collection.
Related posts:
Java Program to Solve Tower of Hanoi Problem using Stacks
Java Program to Perform the Unique Factorization of a Given Number
Java Program to Implement Knapsack Algorithm
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to Implement the Vigenere Cypher
Java Program to Find Basis and Dimension of a Matrix
The DAO with Spring and Hibernate
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Java Program to Implement Borwein Algorithm
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Java Program to Implement Skew Heap
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Implement Control Table
Java Map With Case-Insensitive Keys
Count Occurrences of a Char in a String
Autoboxing và Unboxing trong Java
Java Program to Implement Word Wrap Problem
Spring Security – Reset Your Password
Adding Shutdown Hooks for JVM Applications
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Hướng dẫn Java Design Pattern – Bridge
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Generating Random Dates in Java
A Guide to Apache Commons Collections CollectionUtils
Giới thiệu luồng vào ra (I/O) trong Java
Java Program to Implement Gauss Jordan Elimination
Java Program to Represent Graph Using Linked List
Java Program to Implement Shell Sort
HttpClient with SSL