由以上框图可见,Java的集合类主要由两个接口派生而出:Collection,Map;
Collection和Map是Java集合框架的根接口,Collection集合是单列集合,Map集合是双列集合;这两个接口又包含了一些子接口或实现类。
Collection中可以存储的元素间无序,可以重复的元素。
Collection接口的子接口List和Set,Map不是Collection的子接口。
Set中的元素无序,不重复。
虽然Set中元素没有顺序,但是元素在set中的位置是有由该元素的HashCode决定的,其具体位置其实是固定的。
Set集合中去重和Hashcode与equals方法之间相关。
常见实现类有HashSet,LinedHashSet和TreeSet。
1,HashSet
底层基于Hash算法进行存储元素,允许null,无序,不重复,元素位置固定
HashSet是通过HashMap实现的。
HashSet的几种遍历方法:
public static void main(String[] args) {
Set set=new HashSet();
set.add("111");
set.add("222");
set.add("333");
//遍历集合的第一种方法,使用数组的方法
String[] strArray=new String[set.size()];
strArray=set.toArray(strArray);
for(String str:strArray)//此处也可以使用for(int i=0;i iterator=set.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
}
(1)LinkHashSet
LinkHashSet不仅是Set接口的子接口而且还是上面HashSet接口的子接口TreeSet是通过TreeMap实现的。LinkHashSet底层是基于LinkedHashMap来实现,和HashSet主要区别在于:LinkedHashSet中存储的元素是在哈希算法的基础上增加了链式表的结构。
2,TreeSet
TreeSet底层算法基于红黑树,允许null,有序,不重复,元素位置固定。
List接口中的元素的特点:
List中的元素有序,可以重复。
两个常用的实现类ArrayList和LinkedList。
1,ArrayList
类似数组形式存储,访问数度快,增删慢,线程不安全。
Vector是ArrayList的多线程的一个替代品。
ArrayList的遍历方法:
public static void main(String[] args) {
List list=new ArrayList();
list.add("111");
list.add("222");
list.add("333");
//第一种遍历方法使用foreach遍历List
for (String str : list) {//也可以改写for(int i=0;i ite=list.iterator();
while(ite.hasNext())
{
System.out.println(ite.next());
}
}
2,LinkedList
类似链表结果,查询慢,增删快,线程不安全。
LinkedList遍历方式:
public static void main(String[] args) {
List list=new LinkedList();
list.add("111");
list.add("222");
list.add("333");
//LinkedList遍历的第一种方式使用数组的方式
String[] strArray=new String[list.size()];
list.toArray(strArray);
for(String str:strArray)
{
System.out.println(str);
}
//LinkedList遍历的第二种方式
for(String str:list)
{
System.out.println(str);
}
}
Map中的每个成员方法由一个关键字(key)和一个值(value)构成。
常见实现类HashMap、TreeMap、LinkedHashMap、HashTable。
HashMap无序的、不可重复、查询快、null、非线程安全。
HashMap实现了Map、CloneMap、Serializable三个接口,并且继承自AbstractMap类。
HashMap基于hash数组实现,若key的hash值相同则使用链表方式进行保存。
HashMap遍历方式:
public static void main(String[] args) {
//方式1
Map map = new HashMap();
map.put("A", "1233");
map.put("B", "12334");
map.put("C", "12334");
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey() + "--" + entry.getValue());
}
//方式2效率高
iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
System.out.println(key + "--" + map.get(key));
}
}
TreeMap有序的、不可重复、遍历快、允许null、非线程安全。
HashMap基于红黑树实现。
LinkedHashMap有序的、不可重复、遍历快、允许null、非线程安全。
LinkedHashMap输出顺序和输入顺序相同。
LinkedHashMap继承hashMap,底层存储结果是Hashmap的table。
Hashtable有序的、不可重复、不允许null、线程安全。