java集合类

来源:互联网 发布:淘宝店铺装修素材 编辑:程序博客网 时间:2024/06/06 00:55

<span style="font-family: Arial, Helvetica, sans-serif;">转载地址:http://blog.csdn.net/zdwzzu2006/article/details/4567787</span>

Collections Framework

集合框架是一个统一的架构,用来表示和操作集合.
集合框架主要是由接口,抽象类和实现类构成.
接口:蓝色;实现类:红色

Collection
|_____
Set(HashSet)
|         |_____SortedSet(TreeSet)
|_____List(LinkedList,ArrayList)

Collection:集合层次中的根接口,JDK没有提供这个接口的实现类。
Set:不能包含重复的元素,子接口SortedSet是一个按照升序排列的元素的Set。
List:可以包含重复的元素,是一个有序的集合,提供了按索引访问的方式,有次序,位置不改变。

ArrayList:

本质:我们可以将其看作是能够自动增长容量的数组,实际是采用对象数组实现的。
自动增长容量就是当数组不够的时候,再定义更大的数组,然后将数组元素拷贝到新的数组.

import java.util.*;class ArrayListTest{public static void main(String[] args){   ArrayList a1=new ArrayList();   a1.add("winsun");   a1.add("weixin");   a1.add("mybole");   for(int i=0;i<a1.size();i++)     {        System.out.println(a1.get(i));     }     System.out.println(a1);   }}

结果:

winsun
weixin
mybole
[winsun, weixin, mybole]

利用ArrayList的toArray()返回一个对象的数组也可以利用Arrays.asList()方法返回一个列表。如果想从集合类中获得一个数组可以使用toArray()方法;如果想从数组中获得一个列表可以使用asList()方法 :

import java.util.*;class Point {int x, y;Point(int x, int y) {   this.x = x;   this.y = y;}public String toString() {   return "x=" + x + ",y=" + y;}}public class ArrayListToArrayTest {public static void main(String[] args) {   ArrayList a1 = new ArrayList();   a1.add(new Point(3, 3));   a1.add(new Point(4, 4));   a1.add(new Point(5, 5));   for (int i = 0; i < a1.size(); i++) {    System.out.println(a1.get(i));   }   System.out.println(a1);   Object[] objs = a1.toArray(); // 利用ArrayList的toArray()返回一个对象的数组.   for (int i = 0; i < objs.length; i++) {    System.out.println(objs[i]);   }   System.out.println(objs);//   List l = Arrays.asList(objs);// Arrays.asList()返回一个列表.   System.out.println(l);}}

结果:

x=3,y=3
x=4,y=4
x=5,y=5
[x=3,y=3, x=4,y=4, x=5,y=5]
x=3,y=3
x=4,y=4
x=5,y=5
[Ljava.lang.Object;@1fc4bec
[x=3,y=3, x=4,y=4, x=5,y=5]

LinkedList:

LinkedList是采用双向循环链表实现的.利用LinkedList实现栈(stack),队列(queue),双向队列(double-ended queue)
ArrayList底层采用数组完成,而LinkedList则是以一般的双向链表完成,其内每个对象除了数据本身外,还有两个引用,
分别指向前一个元素和后一个元素.如果我们经常在List的开始处增加元素,或者在List中进行插入
和删除操作,我们应该使用LinkedList,否则的话,使用ArrayList将更加快速.
因为插入和删除都要移动数组中的元素.只是访问就用ArrayList,提供了按索引访问的机制.

import java.util.Deque;import java.util.LinkedList;import java.util.Queue;import java.util.Stack;public class LinkedListDemo {public static void main(String[] args) {Stack<Object> s = new Stack<Object>();//堆栈Queue<Object> q = new LinkedList<Object>();//队列Deque<Object> d = new LinkedList<Object>();//双向队列}}
HashSet:

HashSet实现了Set接口的hash table(哈希表),依靠HashMap来实现.
应该为要存放到散列表的各个对象定义hashCode()和equals().
因为实现了set接口所以不能有重复的元素.
散列表:
散列表又称为哈希表.
散列表算法的基本思想:
以结点的关键字为自变量,通过一定的函数关系(散列函数)
计算出对应的函数值,以这个值作为该结点存储在散列表中的地址.
当散列表中的元素存放太满,就必须进行再散列,将产生一个新的散列表,
所有元素存放到新的散列表中,原先的散列表将被删除.
在java语言中,通过负载因子(load factor)来决定何时对散列表进行再
散列.例如:如果负载因子是0.75,当散列表中已经有75%的位置已经放满,
那么将进行散列.
负载因子越高(越接近1.0),内存的使用率越高,元素的寻找时间越长.
负载因子越低(越接近0.0),元素的寻找时间越短,内存浪费越多.
HashSet类的缺省负载因子是0.75.

import java.util.*;public class HashSetTest {public static void main(String []args){   HashSet hs=new HashSet();/* hs.add("one");   hs.add("two");   hs.add("three");   hs.add("one");   */   hs.add(new Student(1,"zhangsan"));   hs.add(new Student(2,"lisi"));     hs.add(new Student(1,"zhangsan"));   hs.add(new Student(3,"wangwu"));     Iterator it=hs.iterator();   while(it.hasNext())   {    System.out.println(it.next());   }}}class Student{int num;String name;Student(int num,String name){   this.name=name;   this.num=num;}public int HashCode(){   return num*name.hashCode();}public boolean equals(Object o){   Student s=(Student)o;   return num==s.num && name.equals(s.name);}public String toString(){   return "name : ="+name;}}

TreeSet:
TreeSet是依靠TreeMap来实现的.
TreeSet是一个有序集合,TreeSet中元素将按照升序排列,
缺省是按照自然排序进行排列,意味着TreeSet中元素要实现Comparable接口.
我们可以在构造TreeSet对象时,传递实现了Comparator接口的比较器对象.

import java.util.*;public class TreeSetTest {//如果自定义类对象要加入TreeSet要实现Comparable接口public static void main(String []args){   TreeSet ts=new TreeSet(new Student.StudentComparator());/* ts.add("winsun");   ts.add("weixin");   ts.add("mybole");   */   ts.add(new Student(2,"lisi"));   ts.add(new Student(1,"wangwu"));   ts.add(new Student(3,"zhangsan"));   ts.add(new Student(3,"mybole"));     Iterator it=ts.iterator();   while(it.hasNext())   {    System.out.println(it.next());   }}}class Student implements Comparable{int num;String name;static class StudentComparator implements Comparator{   public int compare(Object o1,Object o2)   {    Student s1=(Student)o1;    Student s2=(Student)o2;    int result=s1.num>s2.num ? 1 : (s1.num==s2.num ? 0 : -1);    if(result==0)    { //String类实现了compareTo()方法.     result=s1.name.compareTo(s2.name);    }    return result;      }}public static void printElements(Collection c){   Iterator it=c.iterator();   while(it.hasNext())   {    System.out.println(it.next());   }}Student(int num,String name){   this.name=name;   this.num=num;}public int HashCode(){   return num*name.hashCode();}public boolean equals(Object o){   Student s=(Student)o;   return num==s.num && name.equals(s.name);}public int compareTo(Object o){   Student s=(Student)o;   return num>s.num?1:(num==s.num?0:-1);}public String toString(){   return num+":"+name;}}

HashSet是基于Hash算法实现的,其性能通常优于TreeSet.
通常都应该使用HashSet,在需要排序的功能时,才使用TreeSet.

迭代器:

Collection提供了一个iterator()方法,可以返回一个迭代器,迭代器是指向两个元素之间的指针。凡是继承自Collection的接口或间接的实现类都有这个方法.
其中有3个方法
1.hasNext()
2.next()

3.remove()

hasNext()判断是否有更多的元素,如果有返回true
remove()方法remove()方法需要删除上一个返回的元素,需要先调用next()方法后在用remove(),返回的列表有时不一定真正实现remove()方法,根据需要决定是否实现.

ArrayList al1=new ArrayList();Iterator it=al.iterator();it.next();while(it.hasNext()){System.out.println(it.next());}
通用方式访问集合中的元素
另外定义打印函数

public static void printElements(Collection c){Iterator it=c.iterator();while(it.hasNext()){   System.out.println(it.next());}}


Map(HashMap)
|_____SortedMap(TreeMap)
Map:存储的是key-value对不能包含重复的key,可以有重复的value子接口SortedMap是一个按升序排列key的Map。
HashMap:

import java.util.*;public class HashMapTest{public static void printElements(Collection c){   Iterator it=c.iterator();   while(it.hasNext())   {    System.out.println(it.next());   }}public static void main(String []args){   HashMap hm=new HashMap();   hm.put("1", "zhang3");   hm.put("2", "li4");   hm.put("3", "wang5");     System.out.println(hm.get("1"));   System.out.println(hm.get("2"));   System.out.println(hm.get("3"));     Set keys=hm.keySet();   System.out.println("-----------keys---------");   printElements(keys);   Collection values=hm.values();   System.out.println("-----------values---------");   printElements(values);     Set entrySets =hm.entrySet();   System.out.println("------------entrySets-----------");   printElements(entrySets);   Iterator it=entrySets.iterator();   while(it.hasNext())   {    Map.Entry me=(Map.Entry)it.next();    System.out.println(me.getKey()+" = "+me.getValue());   }  }}

TreeMap是实现了sorted Map接口的类   TreeMap按照key进行排序.类似HashMap用法。HashMap和TreeMap比较和Set类似,HashMap的速度通常都比TreeMap快,只有在需要排序的功能的时候,才使用TreeMap.


Vector集合类
Vector:用ArrayList代替Vector.Vector内所有方法都是同步的,存取元素效率低.在多线程中可以使用


Hashtable:用HashMap代替Hashtable 需要同步Map的时候可以用Collection类的方法
static Map synchronizedMap(Map m) 但是还是Hashtable获取的同步Map快一些.


Stack集合类:Stack:用LinkedList代替Stack.

0 0
原创粉丝点击