Collections集合操作(List、Set、Map)-巧用工具类

来源:互联网 发布:端口电压意思 编辑:程序博客网 时间:2024/05/20 15:38

先从一个简单例子看一下这些东西可以带给我们怎样的便利,下面的代码会完成字符串去重+排序功能。

String str = "asdasdasdx";ArrayList<String> list = new ArrayList(Arrays.asList(str.split("")));HashSet hs = new HashSet(list);list.clear();list.addAll(hs);Collections.sort(list);


不罗嗦了,正文开始!!!

我们先介绍一个类叫Collections(注意末尾有s),它操作在三种数据结构上,分别是List、Set和Map(注意,这三个都是接口,下文会具体讲)。它的API描述是:此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。 

然后再说一下Collention,Collection 表示一组对象和在一组对象上规定的一些操作,这些对象也称为 collection 的元素,其中一些主要方法有add、clear、isEmpty、iterator这些。List和Set中的很多实现都实现了这个接口,比如ArrayList、HashSet。

简单来说,Collections简单来说就是对List、Set和Map进行的一些便利的操作。下面列一些常用的方法,通过名字基本就能看出作用,详细介绍请查看API。

addAll(Collection<? super T> c, T... elements)

copy(List<? super T> dest,List<? extends T> src)

fill(List<? super T> list, T obj)

indexOfSubList(List<?> source,List<?> target)

max(Collection<? extends T> coll,Comparator<? super T> comp)

min(Collection<? extends T> coll,Comparator<? super T> comp)

replaceAll(List<T> list, T oldVal, T newVal)

reverse(List<?> list)

rotate(List<?> list, int distance)

sort(List<T> list)

sort(List<T> list,Comparator<? super T> c)

swap(List<?> list, int i, int j)


说完了这个好用的工具类Collections的作用,我们再介绍一下它的操作对象,List、Set和Map,这三个都是接口,有对应的实现。介绍完这三个接口以后我们讲以应用为目的着重讲一些应用。


①List(常用实现--ArrayList、LinckedList、Stack、Vector)

特点:有顺序可重复

ArrayList:底层数组结构,线程不安全,可重复

LinkedList:底层链表结构,线程不安全

Vector:底层数组结构,线程安全(和ArrayList主要区别就是线程安全与否)


②Set(常用实现--HashSet、TreeSet)

特点:无顺序不可重复(Set具有与Collection完全一样的接口,因此没有任何额外的功能)

HashSet:底层哈希表结构,线程不安全

TreeSet:底层二叉树结构,线程不安全


③Map(常用实现--HashMap、HashTable、TreeMap)

特点:双列集合,键值对存储,和Collection一个级别

HashMap:使用hasCode进行查询

TreeMap:底层红黑树结构,查看时他们会被排序,特点是得到的结果是经过排序的

ps:

Map并没有实现Collection,但是它和Collection相关性却很大,因为对Map的遍历的时候经常把键取出挨个查找。

Set set = Map.keySet();


到此为止,基础课程就讲解完了

--------------------------------------------------------------先来一条华丽的分割线--------------------------------------------------------------

现在,我们要讲一些具体的用法了

一、遍历

Iterator:对Collection进行迭代的迭代器。主要用来对List、Set和Map进行遍历。


HashMap<String, String> hashMap = new HashMap<String, String>();          hashMap.put("computer", "计算机");          hashMap.put("software", "软件");                    //采用Iterator遍历HashMap          Iterator it = hashMap.keySet().iterator();          while(it.hasNext()) {              String key = (String)it.next();              System.out.println("key:" + key);              System.out.println("value:" + hashMap.get(key));          }  



二、实体比较大小

Comparable和Comparator:当使用Collections.sort时,很多时候需要排序的不是String、Integer这种常用数据类型(这些类型实际上已经实现Comparable接口),比如我们定义了一个书本类Book,一般情况会按其编号进行排序,但是有时候会按价格或者出版时间排序,这就需要我们自己实现排序的代码。

static <T extends Comparable<? super T>>
void
sort(List<T> list)
          根据元素的自然顺序 对指定列表按升序进行排序。static <T> voidsort(List<T> list,Comparator<? super T> c)
          根据指定比较器产生的顺序对指定列表进行排序。

这是API中Collections中的sort的两种使用方法。

sort(List<T> list) 的使用方法:

首先在实体类中实现Comparable接口,在调用Collections.sort的时候,它会自动根据定义的compareTo函数比较大小并且返回值。注意compareTo函数返回值为int!

public class Book implements Comparable {     public int id;// 编号      public String name;// 名称      public double price; // 价格      private String author;// 作者      public Calendar calendar;// 出版日期        public Book(int id, String name, double price, Calendar calender,String author) {          this.id = id;          this.name = name;          this.price = price;          this.calendar = calender;          this.author = author;      }        public int compareTo(Book b) {// Comparable接口中的方法          return this.id - b.id; // 按书的id比较大小,用于默认排序      }     

sort(List<T> list, Comparator<? super T> c) 的使用方法:

很多时候我们会根据多种方法进行排序,但是我们实现Compareble接口以后只能实现一种排序方式,所以我们就用到了Comparator比较器,简单来说就是自定义函数比较大小。

public class UseComparator {          Collections.sort(list, new PriceComparator()); // 根据价格排序            Collections.sort(list, new CalendarComparator()); // 根据时间排序      }          // 自定义比较器:按书的价格排序      static class PriceComparator implements Comparator {          public int compare(Book b1,Book b2) {// 实现接口中的方法              return new Double(b1.price).compareTo(new Double(b2.price));          }      }  }  







部分参考自:http://blog.csdn.net/tjcyjd/article/details/6804690

0 0
原创粉丝点击