Java集合总结

来源:互联网 发布:linux迁移mysql数据库 编辑:程序博客网 时间:2024/06/06 01:17

一、Java集合框架结构图:

 

 

 

 

 

 

 

 

 

 

 

 

 

Collection,List,Set都是接口。

Collection是集合里最基本的接口,它里面定义了一个集合最基本功能,如元素的添加,移除,集合大小等的方法。它有两个子类List和Set。

List:有序的,允许元素重复(因为有索引)。

Set:无序(存入和取出的顺序不一定一致),不允许元素重复。

迭代器:

迭代器就是用于把集合里的元素一个一个的取出的东西。

在Collection接口里就定义了iterator()方法,用于获取一个迭代器。获取的该迭代器只有三个方法hasNext(),next(),remove()。List接口里也定义了一个特殊的迭代器ListIterator(),它包含了一些特殊的方法(不仅能取出元素,同时还能对List增删改查)

————————————————————————————————————————————————————————

二、List:ArrayList,LinkedList,Vector 

1)ArrayList:

   它的底层数据结构是数组,线程不同步。查询速度很快,但若有很多元素,增删元素会比较慢,因为增删一个元素,其他元素都得移动一个索引。(牵一发而动全身)

2)LinkedList:

   它的底层数据结构是链表,所以查询很慢,但增删很快。

3)Vector:

   它和ArrayList的数据结构都是数组,但它是线程同步的。

只要理解了他们几个底层的数据结构,那么就好理解他们各自的优点和缺点等特点了。

三、Set:HashSet,TreeSet:

1)HashSet:

    它的数据结构是哈希表,线程是非同步的。

2)TreeSet:

   它的数据结构是二叉树, 不同于HashSet的是他会自动为元素自然排序。

 

附别人的博客总结笔记:点击打开链接 点击打开链接

四、几个练习:

1)练习一:去除某ArrayList集合中重复的元素。

package Test528;import java.util.*;/** * 功能:去除某ArrayList集合中重复的元素。 * 定义函数 singleEmement(ArrayList al)。 * 原理:把原来集合里的元素通过迭代器取出来,并放入一个新的集合容器里。同时每次放入的时候 * 判断新容器里是否已经含有该元素,若有,则不放入。 * @author Administrator * */public class ArrayListTest {public static void main(String[] args) {ArrayList al = new ArrayList();al.add("A");al.add("B");al.add("B");al.add("B");al.add("F");al.add("C");al.add("C");System.out.println(al);ArrayList newAl = singleEmement(al);System.out.println(newAl);}//定义实现该功能的函数public  static ArrayList singleEmement(ArrayList al){ArrayList newAl = new ArrayList<String>(); Iterator it = al.iterator();while(it.hasNext()){Object obj = it.next();if(!newAl.contains(obj)){newAl.add(obj);}}return newAl;}}

2)练习二:使用LinkedList模拟一个堆栈数据结构。

package Test531;import java.util.LinkedList;/** * 使用LinkedList模拟一个队列数据结构(先进先出) * @author Administrator * */public class MyQueue {private LinkedList link; //通过构造函数,只要有类就新建LinkedList对象。MyQueue(){link = new LinkedList();}//自定义MyQueue里的myAdd()方法,其实是封装了link里方法。public void myAdd(Object obj){link.add(obj);}//自定义myGet()方法,其实是封装了link的getFirst()方法。public Object myGet(){return link.getFirst();}public boolean myIsEmp(){return link.isEmpty();}}
package Test531;public class MyDuiLieTest {/** * @param args */public static void main(String[] args) {MyQueue dl = new MyQueue();dl.myAdd("wang1");dl.myAdd("wang2");dl.myAdd("wang3");dl.myAdd("wang4");System.out.println(dl.myIsEmp());System.out.println(dl.myGet());}}

其实编码本身没什么难度,关键是通过封装别人的方法,来自定义自己的方法这种思想要深刻理解。


 

 

 

 

 

 

 

 

 

 

 

 

 

0 0
原创粉丝点击