1.分类
Collection: LinkedList、ArrayList、Vector、Set
Map: HashMap、Hashtable、TreeMap、ConcurrentHashMap
2.区别
2.1 Collection:
LinkedList:底层是链表,有序,增删快、查询慢,线程不安全,数据可以重复
ArrayList:底层是数组,有序,增删慢、查询快,线程不安全,数据可以重复
Vector:底层是数组,线程安全,数据可以重复
set: 不能有重复元素, 无序
Array与ArrayList的区别:
1、Array 存储基本数据类型和对象,ArrayList 只能存储对象。
2、Array 大小固定,ArrayList 大小是自动扩展的。
3、Array 内置方法没有 ArrayList 多。
ArrayList与LinkedList
1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。
2.对于随机访问get和set,ArrayList比较占优势,因为LinkedList要移动指针。
3.对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。
2.2 Map(通过键值对进行存储数据,key不能重复):
HashMap:线程不安全,
Hashtable: 线程安全
ConcurrentHashMap:线程安全
TreeMap:红黑树对所有的key进行排序
HashMap与HashTable对比:
- 单线程使用HashMap比HashTable性能高
- 多线程使用HashTable比HashMap性能高
- HashTable不允许使用null作为key和value
- HashMap可以使用null作为key或value。null可以作为键,这样的键只有一个
3.使用
迭代器
方法
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
Collection<String> con = new ArrayList<>();
Iterator<String> it = con.iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str);
}
列表迭代器
//获取列表迭代器
//通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
String s = it.next();
if(s.equals("hello")) {
lit.add("world");
}
}
LinkedList集合的特有方法
- public void addFirst(E e) 在该列表开头插入指定的元素
- public void addLast(Ee) 将指定的元素追加到此列表的末尾
- public E getFirst() 返回此列表中的第一个元素
- public EgetLast() 返回此列表中的最后一个元素
- public E removeFirst() 从此列表中删除并返回第一个元素
public E removeLast() 从此列表中删除并返回最后一个元素特有方法
HashSet集合
public static void main(String[] args) {
//创建集合对象
HashSet<String> hs = new HashSet<String>();
//添加元素
hs.add("hello");
hs.add("world");
hs.add("java");
hs.add("hello");
//遍历
for(String s : hs) {
System.out.println(s);
}
}
LinkedHashSet集合
public static void main(String[] args) {
//创建集合对象
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
//添加元素
lhs.add("hello");
lhs.add("world");
lhs.add("java");
lhs.add("java");
//遍历集合
for(String s : lsh) {
System.out.println(s);
}
}