1. 程式人生 > >黑馬程式設計師——集合框架(一)

黑馬程式設計師——集合框架(一)

--------------------- <a href="http://edu.csdn.net/heima" target="blank">android培訓</a>、<a href="http://edu.csdn.net/heima" target="blank">java培訓</a>、期待與您交流! ----------------------

Collection

   |--List:元素是有序的,元素可以重複,因為該集合體繫有索引。
       |--ArrayList;底層的資料結構是陣列。特點:查詢速度很快,但是增刪稍慢執行緒不同不
       |--LinkedList:底層使用資料結構是連結串列。特點:增刪速度很快,查詢稍慢。
       |--Vector:底層資料結構是陣列。特點:執行緒同步,被ArrayList取代
   |--Set:元素是無序的(存入和取出的順序不一定一致),元素不可以重複
       |--HashSet:底層是哈系表
                  HashSet保證元素的唯一性是通過hashCode和equals來完成的。
                  如果元素的HashCode值相同,才會判斷equals是否為true
                  如果元素的HashCode值不相同,不會判斷equals

                  注意,對於判斷元素是否存在,以及刪除操作,依賴的方法是元素的hashCode和equals。
       |--TreeSet:可以對Set集合的元素進行排序,底層是二叉數。
                  保證元素唯一性的依據:compareTo方法return 0。
                  
                  TreeSet排序的第一種方式:     讓元素自身具備比較性。
                  元素需實現Comparable介面,覆蓋compareTo方法。
                  這種方式也叫自然順序,或者叫做預設順序。
     
   |--Map
       |--Hashtable:底層資料結構是雜湊表,不可以存入null鍵null值,該集合是執行緒同步的,jdk1.0效率低
       |--HashMap:底層資料結構是哈系表:允許使用null鍵null值,該機和執行緒是不同步的,將hashtable代替,jdk1.2效率高。
       |--TreeMap:底層資料結構是二叉數,執行緒不同步,可以用map集合中的鍵進行排序    
和Set集合很像。其實Set集合底層就是使用了Map集合。
                              
List:
    特有方法,凡是可以操作角標的方法都是該體系特有的方法。


   add(index,element);
   addAll(index,Collection);

   remove(index);

   set(index,element);

   get(index);
   subList(from,to);
   listIterator();
   int indexOf(obj)獲取指定元素的位置
   ListIterator listIterator();  


List集合特有的迭代器。ListIterator 是Iterator的子介面。
在迭代時,不可以通過集合物件的方法操作集合的元素。因為會發生ConcurrentModificationException異常

所以在迭代時,只能用迭代器的方法操作元素,可是Iterator方法是有限的,
只能對元素進行判斷,取出,刪除的操作
如果想要其他的操作如新增,修改等,就需要使用其子介面,ListIterator.
該介面只能通過List集合的ListIterator方法獲得

LinkedList:特有方法
addFirst();
addLast();

getFirst();
getLast();
獲取元素,但是不刪除元素。如果集合中沒有元素,會出現NoSuchElementException

removeFirst();
removeLast();
獲取元素,但是元素被刪除。如果集合中沒有元素,會出現NoSuchElementException

在JDK1.6出現了代替方法:
offerFirst();
offerLast();

peekFirst();
peekLast();
獲取元素,但是不刪除元素。如果集合中沒有元素,返回null。

pollFirst();
pollLast();
獲取元素,但是元素被刪除。如果集合中沒有元素,返回null。

//1.佇列2.去除佇列中的重複元素//

Map集合:該集合儲存鍵值對。一對一對往裡存,而且要保證鍵的唯一性。
    1.新增
         put(K key,V value)
         putAll(Map<? extends K,? extends V> m)
    2.刪除
         clear()
         remove(Object key)
    3.判斷
         containsValue(Object value)
         containKey(Object key)
         isEmpty()
    4.獲取
         get(Object key)
         size()
         value()
         entrySet()
         keySet()  
map集合的兩種取出方式:
1.keyset:將map中所有的鍵存入到Set集合當中。因為Set具備迭代器。
          所有可以迭代方式取出所有的鍵,在根據get方法,獲取每一個鍵對應的值

          Map集合的取出原理:將map集合轉換成set集合,再通過迭代器。    

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

List 練習:

1.ArrayList

package ca.kang;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
    ArrayList al = new ArrayList();
    
    al.add("aaaaa");
    al.add("bbbbb");
    al.add("ccccc");
    al.add("ddddd");
    al.add("aaaaa");
    al.add("ccccc");

    System.out.println(singleElement(al));
    
    }
    
    public static ArrayList singleElement(ArrayList al){
    
        ArrayList newal = new ArrayList();
        
        Iterator it =al.iterator();
        
        while(it.hasNext()){
            
            Object o = it.next();
            if(!newal.contains(o)){
                newal.add(o);
            }
                
        }
        
        return newal;
    }

}

2.ArrayList

package ca.kang;

import java.util.ArrayList;
import java.util.Iterator;

class ArrayListTest2 {

    /**
     * @param args
     * 將自定義物件作為元素存到Arrayist集合當中去,並去除重複元素
     */
    public static void main(String[] args) {
        
        ArrayList al = new ArrayList();
        al.add(new Person("laosi1", 23));
        al.add(new Person("laosi2", 23));
        al.add(new Person("laosi3", 23));
        al.add(new Person("laosi4", 23));
        al.add(new Person("laosi5", 23));
        
        al.add(new Person("laosi1", 23));
        al.add(new Person("laosi2", 23));
        al.add(new Person("laosi3", 23));
        al.add(new Person("laosi4", 23));
        al.add(new Person("laosi5", 23));

        al = singleElement(al);
        
        Iterator it = al.iterator();
        
        while(it.hasNext()){
            
            Person p = (Person) it.next();
            System.out.println("name:"+p.getName()+"...age:"+p.getAge());
        }
    }
    
    public static ArrayList singleElement(ArrayList al){
        
        ArrayList newal = new ArrayList();
        
        Iterator it =al.iterator();
        
        while(it.hasNext()){
            
            Object o = it.next();
            if(!newal.contains(o)){
                newal.add(o);
            }
                
        }
        return newal;
    }

}

3.LinkedList

package ca.kang;

import java.util.LinkedList;

public class LinkedlistDemo1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        Duilie dl = new Duilie();
        
        dl.myAdd("asdas");
        dl.myAdd("123");
        System.out.println(dl.myGet());
    }

}

class Duilie{
    
    private LinkedList link;

    public Duilie() {
    
        link = new LinkedList();
    }
    
    public void myAdd(Object o){
        
        link.addFirst(o);
    }
    
    public Object myGet(){
        
        return link.removeLast();
    }
    
    public boolean isNull(){
        return link.isEmpty();
    }
    
}

4.Vector

package ca.kang;

import java.util.Enumeration;
import java.util.Vector;

public class VectorDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Vector v = new Vector();
        
        v.add("aaaa");
        v.add("bbbb");
        v.add("cccc");
        
        Enumeration en = v.elements();
        
        while(en.hasMoreElements()){
            
            System.out.println(en.nextElement());
        }
    }

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Set練習:

1.HashSet

import java.util.*;
class HashSetDemo
{
 public static void sop(Object obj)
 {
  System.out.println(obj);
 }
 public static void main(String[] args)
 {
  HashSet hs = new HashSet();
  hs.add("java01");
  hs.add("java01");
  hs.add("java02");
  hs.add("java02");
  hs.add("java03");
  hs.add("java04");
  Iterator it=hs.iterator();
  while(it.hasNext())
  {
   sop(it.next());//無序、不可重複
  }
 }
}

2.TreeSet

package cn.kang;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        TreeSet ts = new TreeSet(new MyCompare());
        
        ts.add(new Student("laosi", 23));     
        ts.add(new Student("laosi1", 23));   
        ts.add(new Student("laosi2", 23));  
        ts.add(new Student("laosi2", 23));  
        ts.add(new Student("laosi2", 23));  
        ts.add(new Student("laosi2", 23));  
        
        
        Iterator it = ts.iterator();
        while(it.hasNext()){
            
            Student s = (Student) it.next();
            
            System.out.println("name:"+s.getName()+"...age:"+s.getAge());
        }
    }
}

class MyCompare implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
       
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        
        int num = s1.getName().compareTo(s2.getName());
        if(num == 0)
        {
            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
        }
        return num;
    }
}

3.TreeSet

package cn.kang;

import java.util.Comparator;

public class TreeSetTest2 {

    /**
     * @param args
     * 按照字串長度排序
     */
    public static void main(String[] args) {
        

    }

}

class StrLenComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        
        String s1 = (String) o1;
        String s2 = (String) o2;
        int num = new Integer(s1.length()).compareTo(s2.length());
        
        if(num == 0)
            return s1.compareTo(s2);
        return num;
    }
    
    
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Map練習:

1.

package cn.kang;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class MapTest1 {

    /**
     * @param args
     *
     * 沒一個學生都有自己的歸屬地
     * 學生student,地址string
     * 學生屬性:姓名,年齡
     * 注意:姓名和年齡相同的視為同一個學生
     * 保證學生的唯一性
     */
    public static void main(String[] args) {
        
        HashMap<Student, String> hm = new HashMap<Student, String>();
        
        hm.put(new Student("laosi", 23), "beijin");
        hm.put(new Student("laosi1", 23), "beijin");
        hm.put(new Student("laosi2", 23), "beijin");
        hm.put(new Student("laosi2", 23), "shijiazhuang");
        hm.put(new Student("laosi", 23), "beijin");
        
        //第一種取出方式 keySet
        
        Set<Student> keyset = hm.keySet();
        
        Iterator<Student> it = keyset.iterator();
        
        while(it.hasNext()){
            
            Student s = it.next();
            String addr = hm.get(s);
            System.out.println(s+"addr:"+addr);
        }
        
        
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++");
        
        //第二種取出方式 entrySet
        
        Set<Map.Entry<Student, String>> entryset = hm.entrySet();
        
        Iterator<Map.Entry<Student, String>> it2 = entryset.iterator();
        
        while(it2.hasNext()){
            
            Map.Entry<Student, String> me= it2.next();
            Student s2 = me.getKey();
            String addr2 = me.getValue();
            System.out.println(s2+"addr:"+addr2);
        }
    }

}

2.

package cn.kang;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MapTest2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        TreeMap<Student,String> tm = new TreeMap<Student, String>(new StuNameComparator());
        
        tm.put(new Student("laosi1",21), "cd");
        tm.put(new Student("lasi2",22), "sjz");
        tm.put(new Student("aosi3",23), "bj");
        tm.put(new Student("laosi4",20), "jx");
        tm.put(new Student("laosi1",21), "cd");
        
        Set<Map.Entry<Student, String>> entryset = tm.entrySet();
        
        Iterator<Map.Entry<Student, String>> it = entryset.iterator();
        
        while(it.hasNext()){
            
            Map.Entry<Student, String> me = it.next();
            Student s = me.getKey();
            String addr = me.getValue();
            System.out.println(s+"addr:"+addr);
        }
    }

}

class StuNameComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        
        int num = o1.getName().compareTo(o2.getName());
        if(num == 0){
            return new Integer(o1.getAge()).compareTo(o2.getAge());
        }
        return num;
    }
    
    
}

3.

package cn.kang;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MapTest3 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        String s = "asdasdasdf,./";
        
        System.out.println(charCount(s));

    }
    
    public static String charCount(String str){
        
        char[] chs = str.toCharArray();
        TreeMap<Character,Integer> tm = new TreeMap<Character, Integer>();
        
        int count = 0;
        for(int x=0;x<chs.length;x++){
            
            if(!(Character.isLetter(chs[x]))){
                continue;
            }
            Integer value = tm.get(chs[x]);
            
            if(value!=null)
                count = value;
            count++;
            tm.put(chs[x], count);
            
            count = 0;
            /*
            if(value == null){
                tm.put(chs[x], 1);
            }else{
                value = value + 1;
                tm.put(chs[x], value);
            }
            */
            
        }
        
        StringBuilder sb = new StringBuilder();
        
        Set<Map.Entry<Character, Integer>> entryset = tm.entrySet();
        
        Iterator<Map.Entry<Character, Integer>> it = entryset.iterator();
        
        while(it.hasNext()){
            Map.Entry<Character, Integer> me = it.next();
            Character ch = me.getKey();
            Integer value = me.getValue();
            sb.append(ch+"("+value+")");
        }
        return sb.toString();
    }
}

4.

package cn.kang;

import java.util.HashMap;
import java.util.Iterator;

public class MapTest4 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        HashMap<String, String> yure = new HashMap<String, String>();
        
        yure.put("01", "laosi");
        yure.put("02", "laosi2");
        
        HashMap<String, String> jiuye = new HashMap<String, String>();
        
        jiuye.put("01", "zhangsan");
        jiuye.put("02", "zhangsan2");
        
        HashMap<String, HashMap<String, String>> czbk = new HashMap<String, HashMap<String,String>>();
        czbk.put("yure", yure);
        czbk.put("jiuye", jiuye);
        
        Iterator<String> it = czbk.keySet().iterator();
        
        while(it.hasNext()){
            
            String roomname = it.next();
            HashMap<String,String> room= czbk.get(roomname);
            System.out.println(roomname+":");
            getStudentInfo(room);
            System.out.println("=========================");
        }
        
    }
    
    public static void getStudentInfo(HashMap<String,  String> room){
        
        Iterator<String> it = room.keySet().iterator();
        
        while(it.hasNext()){
            String id = it.next();
            String name = room.get(id);
            System.out.println(id+"..."+name);
        }
    }

}

5.

package cn.kang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class MapTest5 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        HashMap<String, List<Student>> czbk = new HashMap<String, List<Student>>();
        List<Student> yure = new ArrayList<Student>();
        List<Student> jiuye = new ArrayList<Student>();

        czbk.put("yure", yure);
        czbk.put("jiuye", jiuye);
        
        yure.add(new Student("laosi1", 21));
        yure.add(new Student("laosi2", 23));
        
        jiuye.add(new Student("laosi3", 22));
        jiuye.add(new Student("laosi5", 26));
        
        
        Iterator<String> it = czbk.keySet().iterator();
        
        while(it.hasNext()){
            
            String clazzname = it.next();
            List<Student> clazz = czbk.get(clazzname);
            
            System.out.println(clazzname+":");
            getClazzName(clazz);
            System.out.println("=========================");
        }
    }

    private static void getClazzName(List<Student> clazz) {
        
        Iterator<Student> it = clazz.iterator();
        while(it.hasNext()){
            
            Student s = it.next();
            System.out.println(s);
            
            
        }
    }

}

package cn.kang;

public class Student implements Comparable<Student> {

    private String name;
    private int age;
    
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return name.hashCode()+age*17;
    }

    @Override
    public boolean equals(Object obj) {
        
        if(!(obj instanceof Student))
            throw new RuntimeException("無意義!!!");
        
        Student s = (Student) obj;
        
        return this.name.equals(s.name) && this.age == s.age;
    }

    @Override
    public int compareTo(Student o) {
        int num = new Integer(this.age).compareTo(new Integer(o.age));
        if(num == 0)
            return this.name.compareTo(o.name);
        return num;
    }

    @Override
    public String toString() {
        
        return "name:"+name+"...age:"+age+"...";
    }
    
    
}

---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培訓</a>、<a href="http://edu.csdn.net/heima" target="blank">java培訓</a>、期待與您交流! ----------------------