Java ArrayList和HashSet的区别
以下是ArrayList和HashSet之间的一些区别。
- 继承:
-
实现:
实现:ArrayList在Java中实现了List接口,而HashSet则实现了Set接口。 -
内部实现:
ArrayList是由一个数组支持的,而HashSet是由一个HashMap支持的。 -
重复:
ArrayList允许重复的值,而HashSet不允许重复的值。 -
构造函数:
ArrayList有三个构造函数,分别是ArrayList(), ArrayList(int capacity) ArrayList(int Collection c),而HashSet有四个构造函数,分别是HashSet(), HashSet(int capacity), HashSet(Collection c) 和 HashSet(int capacity, float loadFactor) -
顺序:
ArrayList维护它们被插入的对象的顺序,而HashSet是一个无序的集合,不维护任何顺序。 -
索引:
ArrayList是基于索引的,我们可以通过调用get(index)方法来检索对象,或者通过调用remove(index)方法来删除对象,而HashSet是完全基于对象的。HashSet也不提供get()方法。 -
空对象:
ArrayList不适用任何限制,我们可以添加任何数量的空值,而HashSet允许一个空值。 -
语法:
ArrayList:- ArrayList list=new ArrayList();
HashSet:-
HashSet set=new HashSet()
ArrayList例子
// Java program to demonstrate working of ArrayList in Java
import java.io.*;
import java.util.*;
class ArrayListTest {
public static void main(String[] args)
throws IOException
{
// size of ArrayList
int n = 5;
// declaring ArrayList with initial size n
List<Integer> al = new ArrayList<>(n);
// Appending the new element at the end of the list
for (int i = 1; i <= n; i++) {
al.add(i);
}
// Printing elements
System.out.println(al);
// Remove element at index 3
al.remove(3);
// Displaying ArrayList after deletion
System.out.println(al);
// Printing elements one by one
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
HashSet例子
// Java program to demonstrate working of HashSet
import java.util.HashSet;
import java.util.Set;
class HashSetDemo {
public static void main(String[] args)
{
// Create a HashSet
Set<Integer> hs = new HashSet<>();
// add elements to HashSet
hs.add(1);
hs.add(2);
hs.add(3);
hs.add(4);
// Duplicate removed
hs.add(4);
// Displaying HashSet elements
for (Integer temp : hs) {
System.out.print(temp + " ");
}
}
}
输出:
1 2 3 4