Java中ArrayList和HashSet的區別
HashSet和ArrayList都是Java集合框架中最重要的類。
以下是ArrayList和HashSet之間重要的區別。
| 序號 | 關鍵點 | ArrayList | HashSet |
|---|---|---|---|
| 1 | 實現 | ArrayList是List介面的實現。 | 另一方面,HashSet是Set介面的實現。 |
| 2 | 內部實現 | ArrayList內部使用陣列實現。 | HashSet內部使用HashMap實現。 |
| 3 | 元素順序 | ArrayList保持插入順序,即物件插入的順序。 | HashSet是一個無序集合,不保持任何順序。 |
| 4 | 重複元素 | ArrayList允許集合中存在重複值。 | 另一方面,HashSet不允許重複元素。 |
| 5 | 索引效能 | ArrayList使用索引來提高效能,即基於索引的,可以透過呼叫get(index)方法檢索物件,或透過呼叫remove(index)方法刪除物件。 | HashSet完全基於物件,它不提供get()方法。 |
| 6 | 允許空值 | 可以在ArrayList中插入任意數量的空值,沒有任何限制。 | 另一方面,HashSet在其集合中只允許一個空值,之後不允許新增任何空值。 |
ArrayList與HashSet示例
JavaTester.java
import java.io.*;
import java.util.*;
public class JavaTester {
public static void main(String[] args) throws IOException{
int n = 5;
List<Integer> al = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
al.add(i);
}
System.out.println(al);
al.remove(3);
System.out.println(al);
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
}
}
輸出
[1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5
示例
JavaTester.java
import java.util.HashSet;
import java.util.Set;
public class JavaTester {
public static void main(String[] args){
Set<Integer> hs = new HashSet<>();
hs.add(1);
hs.add(2);
hs.add(3);
hs.add(4);
hs.add(4);
for (Integer temp : hs) {
System.out.print(temp + " ");
}
}
}
輸出
1 2 3 4
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP