Java集合框架(List, Set, Map, Collections)

来源:互联网 发布:linux目录权限 编辑:程序博客网 时间:2024/06/06 04:42


转载自http://blog.csdn.net/dajiahuooo/article/category/6199324


1.Java集合框架概述

Java集合框架关系如图,其中Collection和Map同样是集合的顶级。


 

2.List集合

List集合代表一个元素有序,可重复的集合,集合中的每个元素都有其对应的顺序索引。

常用实现类:ArrayList   LinkedList

遍历方式:for循环,Iterator

ArrayList 内部以数组的形式来保存集合中的元素,线程不安全;通常用for循环遍历。Vector线程安全,但Vector是个古老的类,存在很多缺点。

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class ArrayLsitDemo {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         ArrayList<String> arr = new ArrayList<String>();  
  8.         //增  
  9.         arr.add("菠萝");  
  10.         arr.add("香蕉");  
  11.         arr.add("李子");  
  12.         print(arr);  
  13.           
  14.         //删  
  15.         arr.remove(0);//根据索引删除,引用对象知识移除地址  
  16.         print(arr);  
  17.           
  18.         //改  
  19.         arr.set(1"橙子");  
  20.         print(arr);  
  21.           
  22.         //查  
  23.         System.out.println(arr.get(0));  
  24.           
  25.   
  26.     }  
  27.     //遍历  
  28.     public static void print(ArrayList<String> arr){  
  29.         for(String str:arr){  
  30.             System.out.print(str + " ");  
  31.         }  
  32.         System.out.println();  
  33.     }  
  34.   
  35. }  

运行结果:

 

LinkedList可以根据索引来访问集合中的元素,此外还实现了Deque接口,所以也可以当成双端队列来使用,即可当“栈”(先进后出),也可以当作队(先进先出);内部是以线性表和链表实现的,保证输入的顺序。通常用Iterator遍历。

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class LinkedListDemo {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         LinkedList<String> list = new LinkedList<String>();  
  8.         list.add("哈哈");  
  9.         list.add("呵呵");  
  10.         list.add("嘿嘿");  
  11.         print(list);  
  12.           
  13.         list.addFirst("嘻嘻");//链表可以在头或尾插入  
  14.         print(list);  
  15.         //将元素加入到对头  
  16.         list.offerFirst("来来");  
  17.         //将元素加入到队尾  
  18.         list.offerLast("去去");  
  19.         print(list);  
  20.         //访问并不删除栈顶  
  21.         System.out.println("访问并不删除栈顶----" +list.peekFirst());  
  22.         print(list);  
  23.         //访问并删除栈顶  
  24.         System.out.println("访问并删除栈顶----" + list.poll());  
  25.         print(list);  
  26.   
  27.     }  
  28.       
  29.     public static void print(List list){  
  30.         Iterator iterator = list.iterator();  
  31.         while(iterator.hasNext()){  
  32.             System.out.print(iterator.next() + " ");  
  33.         }  
  34.         System.out.println();  
  35.     }  
  36.   
  37. }  


运行结果:

 

注意:LinkedList在进行删除、插入操作时性能更优,而ArrayList在遍历的时候应能更优。


3.Set集合

Set集合不循序包含相同的元素。

常用实现类:HashSet  LinkedHashSet  TreeSet 

遍历方法:Iterator


HashSet通过equals() 和hashCode()方法来判断两个元素是否相等,不保证元素的输入顺序

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class HashSetDemo {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         HashSet<String> set = new HashSet<String>();  
  8.         //增  
  9.         set.add("小猫");  
  10.         set.add("小狗");  
  11.         set.add("小猪");  
  12.         System.out.println(set.add("小猫"));//返回false,不能重复添加  
  13.         print(set);  
  14.           
  15.         //添加自定义对象,需重写hashCode() 和equals()方法  
  16.         HashSet<Dog> dogs = new HashSet<Dog>();  
  17.         dogs.add(new Dog("ho",1));  
  18.         dogs.add(new Dog("wo",3));  
  19.         dogs.add(new Dog("1o",2));  
  20.         System.out.println(dogs.add(new Dog("1o",2)));//无法添加相同对象  
  21.         print(dogs);  
  22.           
  23.   
  24.     }  
  25.       
  26.     public static void print(Set set){  
  27.         Iterator i = set.iterator();  
  28.         while(i.hasNext()){  
  29.             System.out.print(i.next());  
  30.             System.out.print("   ");  
  31.         }  
  32.         System.out.println();  
  33.     }  
  34.   
  35. }  
  36.   
  37. class Dog{  
  38.     private String name;  
  39.     private int age;  
  40.     public Dog(String name, int age) {  
  41.         super();  
  42.         this.name = name;  
  43.         this.age = age;  
  44.     }  
  45.     @Override  
  46.     public int hashCode() {  
  47.         final int prime = 31;  
  48.         int result = 1;  
  49.         result = prime * result + age;  
  50.         result = prime * result + ((name == null) ? 0 : name.hashCode());  
  51.         return result;  
  52.     }  
  53.     @Override  
  54.     public boolean equals(Object obj) {  
  55.         if (this == obj)  
  56.             return true;  
  57.         if (obj == null)  
  58.             return false;  
  59.         if (getClass() != obj.getClass())  
  60.             return false;  
  61.         Dog other = (Dog) obj;  
  62.         if (age != other.age)  
  63.             return false;  
  64.         if (name == null) {  
  65.             if (other.name != null)  
  66.                 return false;  
  67.         } else if (!name.equals(other.name))  
  68.             return false;  
  69.         return true;  
  70.     }  
  71.     @Override  
  72.     public String toString() {  
  73.         return "Dog [name=" + name + ", age=" + age + "]";  
  74.     }  
  75.       
  76.       
  77. }  

运行结果:

 

LinkedSet  保证元素的输入顺序

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class LinkedSetDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.         LinkedHashSet<String> set = new LinkedHashSet<String>();  
  5.         set.add("第一");  
  6.         set.add("第二");  
  7.         set.add("第三");  
  8.         set.add("第四");  
  9.         set.add("胜利");  
  10.         Iterator<String> i = set.iterator();  
  11.         while(i.hasNext()){  
  12.             System.out.println(i.next());  
  13.         }  
  14.           
  15.   
  16.     }  
  17.   
  18. }  

运行结果:


TreeSet是通过自然排序或者自定义排序来保存元素的

自然排序

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class TreeSetDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         //添加自定义元素,需重写compareTo方法  
  6.         TreeSet<Man> man = new TreeSet<Man>();  
  7.         man.add(new Man("小白"14));  
  8.         man.add(new Man("小白"14));//同名同姓的表示同一个人  
  9.         man.add(new Man("小白"15));  
  10.         man.add(new Man("小白"16));  
  11.         man.add(new Man("小白"17));  
  12.         print(man);  
  13.           
  14.   
  15.     }  
  16.       
  17.     public static void print(Set set){  
  18.         Iterator i = set.iterator();  
  19.         while(i.hasNext()){  
  20.         System.out.print(i.next());   
  21.         System.out.print("  ");  
  22.         }  
  23.         System.out.println("打印完毕!");  
  24.     }  
  25.   
  26. }  
  27.   
  28. class Man implements Comparable<Man>{  
  29.     private String name;  
  30.     private int age;  
  31.       
  32.     public Man(String name, int age) {  
  33.         super();  
  34.         this.name = name;  
  35.         this.age = age;  
  36.     }  
  37.      
  38.       
  39.       
  40.   
  41.     @Override  
  42.     public String toString() {  
  43.         return "Man [name=" + name + ", age=" + age + "]";  
  44.     }  
  45.   
  46.   
  47.   
  48.   
  49.     @Override  
  50.     public int hashCode() {  
  51.         final int prime = 31;  
  52.         int result = 1;  
  53.         result = prime * result + age;  
  54.         result = prime * result + ((name == null) ? 0 : name.hashCode());  
  55.         return result;  
  56.     }  
  57.   
  58.   
  59.   
  60.     @Override  
  61.     public boolean equals(Object obj) {  
  62.         if (this == obj)  
  63.             return true;  
  64.         if (obj == null)  
  65.             return false;  
  66.         if (getClass() != obj.getClass())  
  67.             return false;  
  68.         Man other = (Man) obj;  
  69.         if (age != other.age)  
  70.             return false;  
  71.         if (name == null) {  
  72.             if (other.name != null)  
  73.                 return false;  
  74.         } else if (!name.equals(other.name))  
  75.             return false;  
  76.         return true;  
  77.     }  
  78.   
  79.   
  80.   
  81.     public int compareTo(Man o) {  
  82.         if(this.age > o.age){  
  83.             return 1;  
  84.         }else if(this.age < o.age){  
  85.             return -1;  
  86.         }  
  87.         return 0;  
  88.     }  
  89.       
  90.       
  91.       
  92.       
  93. }  

运行结果:


自定义排序

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class TreeSetDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.           
  5.         //自定义比较器,传入匿名内部类 Comparator  
  6.         TreeSet<Man> man = new TreeSet<Man>(new Comparator<Man>() {  
  7.   
  8.             public int compare(Man o1, Man o2) {  
  9.                 if(o1.getAge()> o2.getAge()){  
  10.                     return 1;  
  11.                 }else if(o1.getAge() < o2.getAge()){  
  12.                     return -1;  
  13.                 }  
  14.                 return 0;  
  15.                   
  16.             }  
  17.   
  18.         });  
  19.         man.add(new Man("小白"14));  
  20.         man.add(new Man("小白"14));//同名同姓的表示同一个人 
  21.         man.add(new Man("小白"15));  
  22.         man.add(new Man("小白"16));  
  23.         man.add(new Man("小白"17));  
  24.         print(man);  
  25.           
  26.   
  27.     }  
  28.       
  29.     public static void print(Set set){  
  30.         Iterator i = set.iterator();  
  31.         while(i.hasNext()){  
  32.         System.out.print(i.next());   
  33.         System.out.print("  ");  
  34.         }  
  35.         System.out.println("打印完毕!");  
  36.     }  
  37.   
  38. }  
  39.   
  40. class Man {  
  41.     private String name;  
  42.     private int age;  
  43.       
  44.       
  45.       
  46.     public String getName() {  
  47.         return name;  
  48.     }  
  49.   
  50.   
  51.   
  52.   
  53.     public void setName(String name) {  
  54.         this.name = name;  
  55.     }  
  56.   
  57.   
  58.   
  59.   
  60.     public int getAge() {  
  61.         return age;  
  62.     }  
  63.   
  64.   
  65.   
  66.   
  67.     public void setAge(int age) {  
  68.         this.age = age;  
  69.     }  
  70.   
  71.   
  72.   
  73.   
  74.     public Man(String name, int age) {  
  75.         super();  
  76.         this.name = name;  
  77.         this.age = age;  
  78.     }  
  79.      
  80.       
  81.       
  82.   
  83.     @Override  
  84.     public String toString() {  
  85.         return "Man [name=" + name + ", age=" + age + "]";  
  86.     }  
  87.   
  88.   
  89.   
  90.   
  91.     @Override  
  92.     public int hashCode() {  
  93.         final int prime = 31;  
  94.         int result = 1;  
  95.         result = prime * result + age;  
  96.         result = prime * result + ((name == null) ? 0 : name.hashCode());  
  97.         return result;  
  98.     }  
  99.   
  100.   
  101.   
  102.     @Override  
  103.     public boolean equals(Object obj) {  
  104.         if (this == obj)  
  105.             return true;  
  106.         if (obj == null)  
  107.             return false;  
  108.         if (getClass() != obj.getClass())  
  109.             return false;  
  110.         Man other = (Man) obj;  
  111.         if (age != other.age)  
  112.             return false;  
  113.         if (name == null) {  
  114.             if (other.name != null)  
  115.                 return false;  
  116.         } else if (!name.equals(other.name))  
  117.             return false;  
  118.         return true;  
  119.     }  
  120.   
  121.   
  122.   
  123.       
  124.       
  125.       
  126. }  

运行结果:



4.Map集合

Map是用于保存具有映射关系的数据,有两组值,一组值是用来保存Map里的Key,另外一组值是用来保存Map里的value。key不允许重复。

常用实现类:HashMap  LinkedHashMap  TreeMap

遍历方法有两种:keySet()  entrySet()

1)HashMap线程不安全,允许null作为key,HashTable线程安全,但是古老少用,不允许null作为key。

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class HashMapDemo {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         HashMap<Integer, String> map = new HashMap<Integer,String>();  
  8.         map.put(12"吃饭");  
  9.         map.put(14"睡觉");  
  10.         map.put(13"打豆豆");  
  11.           
  12.         //第一种遍历方式keySet()  
  13.         Set<Integer> keySet = map.keySet();  
  14.         Iterator<Integer> i = keySet.iterator();  
  15.         while(i.hasNext()){  
  16.             Integer key = i.next();  
  17.             System.out.println("键是:" + key + "值是:" + map.get(key));  
  18.         }  
  19.           
  20.         System.out.println("*******************************");  
  21.           
  22.         //第二种遍历方式entrySet()  
  23.         Set<Entry<Integer,String>> entrySet = map.entrySet();  
  24.         Iterator<Entry<Integer, String>> iterator = entrySet.iterator();  
  25.         while(iterator.hasNext()){  
  26.             Entry<Integer, String> next = iterator.next();  
  27.             System.out.println("键是:" + next.getKey() + "值是:" + next.getValue());  
  28.         }  
  29.   
  30.     }  
  31.   
  32. }  
运行结果:


2)LinkedHashMap

LinkedHashMap也是使用双向链表来维护key-value,保证迭代顺序与key-value对的插入顺序一直。

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class LinkedHashMapDemo {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer,String>();  
  8.         map.put(12"吃饭");  
  9.         map.put(14"睡觉");  
  10.         map.put(13"打豆豆");  
  11.         map.put(11"刷牙");  
  12.         map.put(15"上厕所");  
  13.           
  14.           
  15.         //第一种遍历方式keySet()  
  16.         Set<Integer> keySet = map.keySet();  
  17.         Iterator<Integer> i = keySet.iterator();  
  18.         while(i.hasNext()){  
  19.             Integer key = i.next();  
  20.             System.out.println("键是:" + key + "值是:" + map.get(key));  
  21.         }  
  22.           
  23.           
  24.   
  25.     }  
  26.   
  27. }  

运行结果:



3)TreeMap

     与TreeSet同理,是红黑树结构存储,自然排序,key需要继承Comparable接口,自定义排序,则需传入Comparator对象。

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class TreeMapDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //String类已经继承Comparabe接口  
  5.         TreeMap<String, String> map = new TreeMap<String, String>();  
  6.         map.put("a""aaaa");  
  7.         map.put("c""cccc");  
  8.         map.put("d""dddd");  
  9.         map.put("f""ffff");  
  10.         map.put("q""qqqq");  
  11.           
  12.         Set<String> keySet = map.keySet();  
  13.         Iterator<String> i = keySet.iterator();  
  14.         while(i.hasNext()){  
  15.             String key = i.next();  
  16.             System.out.println("键是:" + key + "值是:" + map.get(key));  
  17.         }  
  18.   
  19.     }  
  20.   
  21. }  

运行结果:


5.collections工具类

该工具类提供了大量的方法对集合元素进行增删改查等操作。还提供了将集合对象设置为不可变、对集合对象实现同步控制等方法。

1)排序操作

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class Demo10 {  
  2.     public static void main(String[] args) {  
  3.         List list = new ArrayList<Integer>();  
  4.         list.add(4);  
  5.         list.add(3);  
  6.         list.add(12);  
  7.         list.add(-9);  
  8.           
  9.         //对list随机排序  
  10.         Collections.shuffle(list);  
  11.         print(list);  
  12.         //自然排序  
  13.         Collections.sort(list);  
  14.         print(list);  
  15.           
  16.   
  17.     }  
  18.     public static void print(List<Integer> arr){  
  19.         for(Integer str:arr){  
  20.             System.out.print(str + " ");  
  21.         }  
  22.         System.out.println();  
  23.     }  
  24.   
  25. }  

运行结果:


2)查找替换操作

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class Demo10 {  
  2.     public static void main(String[] args) {  
  3.         List list = new ArrayList<Integer>();  
  4.         list.add(4);  
  5.         list.add(3);  
  6.         list.add(12);  
  7.         list.add(-9);  
  8.           
  9.         //自然排序  
  10.         Collections.sort(list);  
  11.         print(list);  
  12.           
  13.         //查找、替换  
  14.         System.out.println("最大元素是:" + Collections.max(list));  
  15.         System.out.println("4的索引是:" + Collections.binarySearch(list, 4));  
  16.         System.out.println("替换所有的元素:" );  
  17.         Collections.fill(list, 1);  
  18.         print(list);  
  19.           
  20.           
  21.   
  22.     }  
  23.     public static void print(List<Integer> arr){  
  24.         for(Integer str:arr){  
  25.             System.out.print(str + " ");  
  26.         }  
  27.         System.out.println();  
  28.     }  
  29.   
  30. }  

运行结果:


3)同步操作

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.         Collection collection = Collections.synchronizedCollection(new ArrayList());  
  3.         List list = Collections.synchronizedList(new ArrayList());  
  4.         Map map = Collections.synchronizedMap(new HashMap());  
  5.         Set set = Collections.synchronizedSet(new HashSet());  
  6.   
  7.     }  

4)设置不可变操作

示例:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.         List list = new ArrayList<Integer>();  
  3.         list.add(4);  
  4.         list.add(3);  
  5.         list.add(12);  
  6.         list.add(-9);  
  7.         List unmodifiableList = Collections.unmodifiableList(list);  
  8.         System.out.println(unmodifiableList.add(2));  
  9.   
  10.     }  

运行结果:

发生异常



0 0