黑馬_blog4_集合框架

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity開發</a>、<a href="http://www.itheima.com"target="blank">.Net培訓</a>、期待與您交流! ----------------------

 

1集合框架(體系概述)

爲什麼會出現這麼多的容器呢?

因爲每一個容器對數據的存儲方式都有不同,這個存儲方式可以稱之爲:數據結構--數據在內存中的存儲方式。

2集合框架(共性方法)

引入的包:import java.util.*;

創建一個集合容器,使用Collection接口的子類ArrayList

ArrayList aL=new ArrayList();

添加元素:aL.add(“java01”);

獲取集合長度:aL.size();

打印集合:System.out.println(aL);

刪除元素:aL.remove(“java02”);

  aL.clear();

判斷元素:aL.contains(“java03”);//是否包含

          aL.isEmpty();//集合是否爲空

取交集:aL1.retainAll(aL2);

取差集:aL1.removeAll(aL2);

注:add方法的參數類型是Object,以便於接收任意類型對象,集合中存儲的都是對象的引用。

3集合框架(迭代器)

什麼是迭代器?

其實就是集合的取出元素的方式。

把取出方式定義在了集合的內部,這樣取出方式就可以直接訪問每個集合內容的元素,那麼取出方式就被定義成了內部類。而每一個容器的數據結構不同,所以取出的動作細節也不一樣,但是都有共性內容:判斷和取出,那麼可以將這些共性抽取。那麼這些內部類都符合一個規則Iterator,如何獲取集合的取出對象呢?通過一個對外提供的方法iterator()

代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		ArrayList<String> aL=new ArrayList<String>();
		aL.add("java01");
		aL.add("java02");
		aL.add("java03");
		Iterator it=aL.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

4集合框架(List結合共性方法)

Collection

   |---List:元素是有序的,元素可以重複,因爲該集合體繫有索引

   |---Set:元素是無序的,元素不可以重複,沒有索引

List集合特有方法:凡是可以操作角標的方法都是該體系特有的方法。

增加元素:add(index,element)

          addAll(index,Collection)

刪除元素:remove(index);

修改元素:setindext,element)

查找元素:get(index)

          subList(from,to)

          ListIterator();

獲取所有元素

方式1for(int i=0;i<aL.size();i++)

{System.out.println(aL.get(i));}

方式2

Iterator it=aL.iterator();

while(it.hasNext())

{System.out.println(it.next());}

獲取對象的位置:aL.indexOf(“java02”);

5集合框架(ListIterator)

代碼:

		//在迭代過程中,準備添加或者刪除元素
		ArrayList aL=new ArrayList();
		aL.add("java02");
		aL.add("java03");
		Iterator it=aL.iterator();
		while(it.hasNext())
		{
			Object obj=it.next();
			if(obj.equals("java02"))
				it.remove();
		}
		System.out.println(obj);

List集合特有的迭代器,ListIteratorIterator的子接口,在迭代時,不可以通過集合對象的方法操作集合中的元素,因爲會發生併發修改異常,所以,在迭代時,只能用迭代器的方法操作元素,可是Iterator方法是有限的,只能對元素進行判斷,取出,刪除的操作,如果想要其他的操作,如添加,修改等就需要使用其子接口,ListIterator,該接口只能通過List集合的ListIterator方法獲取。

代碼:

ArrayList aL=new ArrayList();
		aL.add("java02");
		aL.add("java03");
		ListIterator it=aL.listIterator();
		Object obj=null;
		while(it.hasNext())
		{
			obj=it.next();
			if(obj.equals("java02"))
				it.add("java009");
			
		}
		System.out.println(aL);

判斷有沒有前一個元素:it.hasPrevious();

判斷有沒有後一個元素:it.hasNext();

獲取前一個元素:it.previous();

6集合框架(List集合具體對象的特點)

Collection

|--List:元素是有序的,元素可以重複。因爲該集合體繫有索引。

|--ArrayList:底層的數據結構使用的是數組結構。特點:查詢速度很快。但是增刪稍慢。線程不同步。

|--LinkedList:底層使用的鏈表數據結構。特點:增刪速度很快,查詢稍慢。線程不同步。

|--Vector:底層是數組數據結構。線程同步。被ArrayList替代了。因爲效率低。

ArrayList 默認長度爲10,超過10,再添加,就會new一個新的數組,50%延長,把原來的添加到新數組中來,再向後添加。

Vector 默認長度爲10,超過10,100%延長。

一般使用ArrayListVector的效率低。

7集合框架(Vector中的枚舉)

枚舉就是Vector特有的取出方式。發現枚舉和迭代器很像。其實枚舉和迭代是一樣的。

因爲枚舉的名稱以及方法的名稱都過長。所以被迭代器取代了。枚舉鬱鬱而終了。

代碼:

class VectorDemo 
{
	public static void main(String[] args) 
	{
		Vector v = new Vector();
		v.add("java01");
		v.add("java02");
		v.add("java03");
		v.add("java04");
		Enumeration en = v.elements();
		while(en.hasMoreElements())
		{
			System.out.println(en.nextElement());
		}
	}
}

8集合框架(LinkedList)

LinkedList:特有方法:

addFirst();

addLast();

 

getFirst();

getLast();

獲取元素,但不刪除元素。如果集合中沒有元素,會出現NoSuchElementException

removeFirst();

removeLast();

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

JDK1.6出現了替代方法。

offerFirst();

offerLast();

 

peekFirst();

peekLast();

獲取元素,但不刪除元素。如果集合中沒有元素,會返回null不拋出異常

pollFirst();

pollLast();

獲取元素,但是元素被刪除。如果集合中沒有元素,會返回null不拋出異常

9集合框架(LinkedList練習)

使用LinkedList模擬堆棧或者隊列數據結構:

堆棧:先進後出,如同杯子

隊列:先進先出,如同水管

代碼:

import java.util.*;
class DuiLie
{
	private LinkedList link;

	DuiLie()
	{
		link = new LinkedList();
	}
	public void myAdd(Object obj)
	{
		link.addFirst(obj);
	}
	public Object myGet()
	{
		return link.removeFirst();
	}
	public boolean isNull()
	{
		return link.isEmpty();
	}
}

10集合框架(ArrayList練習1)

代碼:

去除ArrayList集合中的重複元素。

注:迭代時,it.next()取一次,就用it.hasNext()判斷一次。

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		ArrayList aL=new ArrayList();
		aL.add("java01");
		aL.add("java01");
		System.out.println(singleElement(aL));
	}
	public static List singleElement(ArrayList aL)
	{
		ArrayList temp=new ArrayList();
		Iterator it=aL.iterator();
		while(it.hasNext())
		{
			Object obj=it.next();
			if(!temp.contains(obj))
				temp.add(obj);
			
		}
		return temp;
	}
}

11集合框架(ArrayList練習2)

將自定義對象作爲元素存到ArrayList集合中,並去除重複元素。

比如:存人對象。同姓名同年齡,視爲同一個人。爲重複元素。

思路:

1,對人描述,將數據封裝進人對象。

2,定義容器,將人存入。

3,取出。

注:List集合判斷元素是否相同,依據是元素的equals方法。equals方法默認比較的是地址值,我們要讓它按照我們的方式比較,需要重寫equals方法。

代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		ArrayList aL=new ArrayList();
		aL.add(new Person("zhangsan",34));
		aL.add(new Person("lisi",34));
		aL.add(new Person("wangwu",33));
		aL.add(new Person("wangwu",33));
		aL.add(new Person("wangwu",33));
		aL.add(new Person("wangwu",33));
		aL=singleElement(aL);
		Iterator it=aL.iterator();
		while(it.hasNext())
		{
			Person p=(Person)it.next();
			System.out.println(p.getName()+"   "+p.getAge());
		}
        System.out.println(aL.remove(new Person("wangwu",33)));
	}
	public static ArrayList singleElement(ArrayList aL)
	{
		ArrayList temp=new ArrayList();
		Iterator it=aL.iterator();
		while(it.hasNext())
		{
			Object obj=it.next();
			if(!temp.contains(obj))
				temp.add(obj);
			
		}
		return temp;
	}
}
class Person
{
	private String name;
	private int age;
	Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Person))
			return false;
		Person p = (Person)obj;
		return this.name.equals(p.name) && this.age == p.age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}

注意:調用contains(),contais()調用的是equals();

remove底層也調用了equals();

12集合框架(HashSet)

set:元素無序,不可重複。

HashSet:底層數據結構是哈希表

Set集合的功能和Collection功能一致。
代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		HashSet hs=new HashSet();
		hs.add("java01");
		hs.add("java02");
		hs.add("java03");
		hs.add("java04");
		hs.add("java03");
		Iterator it=hs.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

13集合框架(HashSet存儲自定義對象)

HashSet集合中存入自定義的對象,姓名和年齡相同爲同一個人。

代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		HashSet hs=new HashSet();
		hs.add(new Person("java01",22));
		hs.add(new Person("java02",22));
		hs.add(new Person("java02",22));
		Iterator it=hs.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}
class Person
{
	private String name;
	private int age;
	public Person(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
	public int hashCode()
	{
		return this.name.hashCode()+age*17;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Person))
		{
			return false;
		}
		Person p=(Person)obj;
		return this.name.equals(p.name)&&(this.age==p.age);
	}	
}

HashSet是如何保證元素唯一性的呢?

是通過元素的兩個方法,hashCodeequals來完成。

如果元素的HashCode值相同,纔會判斷equals是否爲true

如果元素的hashcode值不同,不會調用equals

13集合框架(HashSet判斷和刪除的依據)

hs.contains(new Person("java01",22));

hs.remove(new Person("java01",22))

注意:對於判斷元素是否存在,以及刪除等操作,依賴的方法是元素的hashcodeequals方法。

14集合框架(TreeSet)

Set:無序,不可以重複元素。

|--HashSet:數據結構是哈希表。線程是非同步的。

保證元素唯一性的原理:判斷元素的hashCode值是否相同。

如果相同,還會繼續判斷元素的equals方法,是否爲true

|--TreeSet:可以對Set集合中的元素進行排序。

底層數據結構是二叉樹。

保證元素唯一性的依據:

compareTo方法return 0.

代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		TreeSet ts=new TreeSet();
		ts.add("java01");
		ts.add("java06");
		ts.add("java02");
		ts.add("java08");
		ts.add("java00");
		Iterator it=ts.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}
15集合框架(TreeSet存儲自定義對象)

TreeSet集合中存儲自定義對象,學生,想按照學生的年齡進行排序。

記住:排序時,當主要條件相同時,一定要判斷一下次要條件。

代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		TreeSet ts=new TreeSet();
		ts.add(new Student("zhangsan",23));
		ts.add(new Student("zhangsan",19));
		ts.add(new Student("zhangsan",33));
		ts.add(new Student("zhangsan",11));
		ts.add(new Student("zhangsan1",11));

		Iterator it=ts.iterator();
		while(it.hasNext())
		{
			Student s=(Student)it.next();
			System.out.println(s.getName()+"  "+s.getAge());
		}
	}
}
class Student implements Comparable
{
	private String name;
	private int age;
	public Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public int compareTo(Object obj)
	{
		if(!(obj instanceof Student))
			throw new RuntimeException("不是學生對象");
		Student s=(Student)obj;
		if(this.age>s.age)
			return 1;
		else if(this.age<s.age)
			return -1;
		else return this.name.compareTo(s.getName());
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
}

實現Comparable接口,並複寫CompareToObject obj)方法,Student類才具有比較性。

16集合框架(二叉樹)

元素怎麼存進去就怎麼取出來

public int compareTo(Object obj)

{return 1;}

注:|--TreeSet:可以對Set集合中的元素進行排序。底層數據結構是二叉樹。保證元素唯一性的依據:compareTo方法return 0.

TreeSet排序的第一種方式:讓元素自身具備比較性。

元素需要實現Comparable接口,覆蓋compareTo方法。

也種方式也成爲元素的自然順序,或者叫做默認順序。

17集合框架(實現comparator方式排序)

TreeSet的第二種排序方式。

當元素自身不具備比較性時,或者具備的比較性不是所需要的。

這時就需要讓集合自身具備比較性。

在集合初始化時,就有了比較方式。

代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		TreeSet ts=new TreeSet(new MyCompare());
		ts.add(new Student("java04",22));
		ts.add(new Student("java02",25));
		ts.add(new Student("java01",21));
		Iterator it=ts.iterator();
		while(it.hasNext())
		{
			Student s=(Student)it.next();
			System.out.println(s.getName()+" "+s.getAge());
		}

	}
}
class Student implements Comparable
{
	private String name;
	private int age;
	public Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
	public int compareTo(Object obj)
	{
		Student s=(Student)obj;
		int num=new Integer(this.getAge()).compareTo(new Integer(s.getAge()));
		if(num==0)
		{
			return this.getName().compareTo(s.getName());
		}
		return num;
	}
}

class MyCompare implements Comparator
{
	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;
	}
}

18集合框架(TreeSet練習)

按照字符串的長度排序:使用比較器

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		TreeSet ts=new TreeSet(new StringLengthComparator());
		ts.add("aaaa");
		ts.add("cbaa");
		ts.add("e9");
		Iterator it=ts.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}
class StringLengthComparator implements Comparator
{
	public int compare(Object o1,Object o2)
	{
		String s1=(String)o1;
		String s2=(String)o2;
		int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(num==0)
			return s1.compareTo(s2);
		return num;
	}
}

19集合框架(泛型概述)

泛型:JDK1.5版本以後出現新特性。用於解決安全問題,是一個類型安全機制。

好處

1.將運行時期出現問題ClassCastException,轉移到了編譯時期。,

方便於程序員解決問題。讓運行時問題減少,安全。,

2,避免了強制轉換麻煩。

代碼:

ArrayList<String> aL=new ArrayList<String>();
	aL.add("java01");
	aL.add("java02");
	Iterator<String> it=aL.iterator();
	while(it.hasNext())
		{
		String s=it.next();
		System.out.println(s);
	}

20集合框架(泛型使用)

泛型格式:通過<>來定義要操作的引用數據類型。

在使用java提供的對象時,什麼時候寫泛型呢?

通常在集合框架中很常見,

只要見到<>就要定義泛型。

其實<> 就是用來接收類型的。

當使用集合時,將集合中要存儲的數據類型作爲參數傳遞到<>中即可。

泛型比較器代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		TreeSet<String> ts=new TreeSet<String>(new StringLengthComparator());
		ts.add("java02");
		ts.add("java01");
		ts.add("java001");
		Iterator<String> it=ts.iterator();
		while(it.hasNext())
		{
			String s=it.next();
			System.out.println(s);
		}
	}
}
class StringLengthComparator implements Comparator<String>
{
	public int compare(String s1,String s2)
	{
		int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(num==0)
			return s1.compareTo(s2);
		return num;
	}
}

21集合框架(泛型類)

泛型類代碼:

class Test 
{
	public static void main(String[] args) 
	{
		Tool<Student> tL=new Tool<Student>();
		tL.setObject(new Student());
		Student s=tL.getObject();

	}
}
class Student
{
}
class Worker
{
}
class Tool<QQ>
{
	private QQ q;
	public void setObject(QQ q)
	{
		this.q=q;
	}
	public QQ getObject()
	{
		return this.q;
	}
}

當類中要操作的引用數據類型不確定的時候,使用泛型類,早期使用的是Object來完成擴展,容易在運行時期強制類型轉換出錯。

22集合框架(泛型方法)

泛型類定義的泛型,在整個類中有效。如果被方法使用,

那麼泛型類的對象明確要操作的具體類型後,所有要操作的類型就已經固定了。

爲了讓不同方法可以操作不同類型,而且類型還不確定。

那麼可以將泛型定義在方法上。

代碼:

class Test 
{
	public static void main(String[] args) 
	{
		Demo d=new Demo ();
		d.show(4);
		d.print("haha");
	}
}

class Demo
{
	public<T> void show(T t)
	{
		System.out.println("show"+t);
	}
	public<T> void print(T t)
	{
		System.out.println("print"+t);
	}
}

23集合框架(靜態方法泛型)

靜態方法不可以訪問類上定義的泛型。

如果靜態方法操作的應用數據類型不確定,可以將泛型定義在方法上。

public static <W> method(W w)

24集合框架(泛型接口)

在實現接口的時候知道操作的是什麼類型:

class Test 
{
	public static void main(String[] args) 
	{
		InterImple in=new InterImple();
		in.show("hello");
	}
}
interface Inter<T>
{
	public void show(T t);
}
class InterImple implements Inter<String>
{
	public void show(String str)
	{
		System.out.println(str);
	}
}

在實現接口的時候不知道操作什麼類型,在實例化的時候才知道。

class Test 
{
	public static void main(String[] args) 
	{
		InterImple<Integer> in=new InterImple<Integer>();
		in.show(5);
	}
}
interface Inter<T>
{
	public void show(T t);
}
class InterImple<T> implements Inter<T>
{
	public void show(T t)
	{
		System.out.println(t);
	}
}

25集合框架(泛型限定)

通配符。也可以理解爲佔位符。

泛型的限定;

? extends E: 可以接收E類型或者E的子類型。上限。

? super E: 可以接收E類型或者E的父類型。下限

? extends E示例代碼:

import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		ArrayList<Person> aL=new ArrayList<Person>();
		aL.add(new Person("aaa1"));
		aL.add(new Person("aaa2"));
		aL.add(new Person("aaa3"));
		print(aL);
		ArrayList<Student> aL1=new ArrayList<Student>();
		aL1.add(new Student("aaa-01"));
		aL1.add(new Student("aaa_02"));
		aL1.add(new Student("aaa-03"));
		print(aL1);
	}
	public static void print(ArrayList<? extends Person> aL)
	{
		Iterator<? extends Person> it=aL.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next().getName());
		}
	}
}
class Person
{
	private String name;
	public Person(String name)
	{
		this.name=name;
	}
	public String getName()
	{
		return this.name;
	}
}
class Student extends Person
{
	public Student(String name)
	{
		super(name);
	}
}
? super E示例代碼:
import java.util.*;
class Test 
{
	public static void main(String[] args) 
	{
		TreeSet<Student> ts=new TreeSet<Student>(new Comp());
		ts.add(new Student("abc04"));
		ts.add(new Student("abc01"));
		ts.add(new Student("abc03"));
		Iterator<Student> sit=ts.iterator();
		while(sit.hasNext())
		{
			System.out.println(sit.next().getName());
		}

		TreeSet<Worker> tss=new TreeSet<Worker>(new Comp());
		tss.add(new Worker("wabc-03"));
		tss.add(new Worker("wabc-01"));
		tss.add(new Worker("wabc-04"));

		Iterator<Worker> wit=tss.iterator();
		while(wit.hasNext())
		{
			System.out.println(wit.next().getName());
		}
	}
}
class Comp implements Comparator<Person>
{
	public int compare(Person p1,Person p2)
	{
		return p1.getName().compareTo(p2.getName());
	}
}
class Person
{
	private String name;
	public Person(String name)
	{
		this.name=name;
	}
	public String getName()
	{
		return this.name;
	}
}
class Student extends Person
{
	public Student(String name)
	{
		super(name);
	}
}
class Worker extends Person
{
	public Worker(String name)
	{
		super(name);
	}
}

26集合框架(Map概述)

Map集合:該集合存儲鍵值對。一對一對往裏存。而且要保證鍵的唯一性。

1,添加。

put(K key, V value) 

putAll(Map<? extends K,? extends V> m) 

2,刪除。

clear() 

remove(Object key) 

3,判斷。

containsValue(Object value) 

containsKey(Object key) 

isEmpty() 

4,獲取。

get(Object key) 

size() 

values() 

entrySet() 

keySet() 

27集合框架(Map子類對象的特點)

Map

|--Hashtable:底層是哈希表數據結構,不可以存入nullnull值。該集合是線程同步的。jdk1.0.效率低。

|--HashMap:底層是哈希表數據結構,允許使用 null 值和 null 鍵,該集合是不同步的。將hashtable替代,jdk1.2.效率高。

|--TreeMap:底層是二叉樹數據結構。線程不同步。可以用於給map集合中的鍵進行排序。

Set很像。

其實大家,Set底層就是使用了Map集合。

注意:添加元素,添加元素,如果出現添加時,相同的鍵。那麼後添加的值會覆蓋原有鍵對應值

System.out.println("put:"+map.put("01","zhangsan1"));

System.out.println("put:"+map.put("01","wnagwu"));

28集合框架(Map_keySet)

map集合的兩種取出方式:

Set<k> keySet:將map中所有的鍵存入到Set集合。因爲set具備迭代器。所有可以迭代方式取出所有的鍵,在根據get方法。獲取每一個鍵對應的值。

代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		Map<String,String> map=new HashMap<String,String>();
		map.put("01","zhangsan01");
		map.put("02","zhangsan02");
		map.put("03","zhangsan03");
		map.put("04","zhangsan04");
		Set<String> keys=map.keySet();
		Iterator<String> it=keys.iterator();
		while(it.hasNext())
		{
			String key=it.next();
			String value=map.get(key);
			System.out.println(key+"="+value);
		}
	}
}

注意:Map集合的取出原理:將map集合轉成set集合。在通過迭代器取出。

29集合框架(Map-entrySet)

Set<Map.Entry<k,v>> entrySet:將map集合中的映射關係存入到了set集合中,而這個關係的數據類型就是:Map.Entry

Entry其實就是Map中的一個static內部接口。

爲什麼要定義在內部呢?

因爲只有有了Map集合,有了鍵值對,纔會有鍵值的映射關係。關係屬於Map集合中的一個內部事物。而且該事物在直接訪問Map集合中的元素。

代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		Map<String,String> map=new HashMap<String,String>();
		map.put("01","zhangsan01");
		map.put("02","zhangsan02");
		map.put("03","zhangsan03");
		map.put("04","zhangsan04");
		Set<Map.Entry<String,String>> entry=map.entrySet();
		Iterator<Map.Entry<String,String>> it=entry.iterator();
		while(it.hasNext())
		{
			Map.Entry<String,String> me=it.next();
			String key=me.getKey();
			String value=me.getValue();
			System.out.println(key+"="+value);
		}
	}
}

30集合框架(Map練習)

練習要求:

每一個學生都有對應的歸屬地。學生Student,地址String。學生屬性:姓名,年齡。

注意:姓名和年齡相同的視爲同一個學生。保證學生的唯一性。

1,描述學生。

2,定義map容器。將學生作爲鍵,地址作爲值。存入。

3,獲取map集合中的元素。

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		HashMap<Student,String> hm=new HashMap<Student,String>();
		hm.put(new Student("lisi1",22),"tianjing");
		hm.put(new Student("lisi1",22),"beijing");
		hm.put(new Student("lisi2",26),"shanghai");
		hm.put(new Student("lisi3",23),"nanjing");
		hm.put(new Student("lisi4",26),"wuhan");
		//第一種取出方式
		Set<Student> keys=hm.keySet();
		Iterator<Student> it=keys.iterator();
		while(it.hasNext())
		{
			Student stu=it.next();
			String address=hm.get(stu);
			System.out.println(stu+"  "+address);
		}

		//第二種取出方式
		Set<Map.Entry<Student,String>> entry=hm.entrySet();
		Iterator<Map.Entry<Student,String>> iter=entry.iterator();
		while(iter.hasNext())
		{
			Map.Entry<Student,String> me=iter.next();	
			Student stu=me.getKey();
			String address=me.getValue();
			System.out.println(stu+"-------"+address);
		}

	}
}
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	public Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public int hashCode()
	{
		return this.name.hashCode()+this.age*37;
	}
	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.getAge();
	}
	public int compareTo(Student s)
	{
		int num=this.name.compareTo(s.getName());
		if(num==0)
		{
			return new Integer(this.age).compareTo(new Integer(s.getAge()));
		}
		return num;
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
	public String toString()
	{
		return this.name+" "+this.age;
	}
}

31集合框架(TreeMap練習)

利用treeMap存入學生對象:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		TreeMap<Student,String> hm=new TreeMap<Student,String>(new StuCom());
		hm.put(new Student("lisi1",22),"tianjing");
		hm.put(new Student("lisi1",22),"beijing");
		hm.put(new Student("lisi2",26),"shanghai");
		hm.put(new Student("lisi3",23),"nanjing");
		hm.put(new Student("lisi4",26),"wuhan");

		Set<Map.Entry<Student,String>> entry=hm.entrySet();
		Iterator<Map.Entry<Student,String>> iter=entry.iterator();
		while(iter.hasNext())
		{
			Map.Entry<Student,String> me=iter.next();	
			Student stu=me.getKey();
			String address=me.getValue();
			System.out.println(stu+"-------"+address);
		}

	}
}
class StuCom implements Comparator<Student>
{
	public int compare(Student s1,Student s2)
	{
		int num=new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		if(num==0)
			return s1.getName().compareTo(s2.getName());
		return num;
	}
}
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	public Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public int hashCode()
	{
		return this.name.hashCode()+this.age*37;
	}
	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.getAge();
	}
	public int compareTo(Student s)
	{
		int num=this.name.compareTo(s.getName());
		if(num==0)
		{
			return new Integer(this.age).compareTo(new Integer(s.getAge()));
		}
		return num;
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
	public String toString()
	{
		return this.name+" "+this.age;
	}
}

32集合框架(TreeMap練習-字母出現的次數)

根據給定的字符串,統計各個字母出現的次數。

代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		System.out.println(charCount("rrrrdldlk"));
	}
	public static String charCount(String str)
	{
		char[] chs=str.toCharArray();
		TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
		for(int i=0;i<chs.length;i++)
		{
			Integer value=tm.get(chs[i]);
			if(value==null)
			{
				value=0;
			}
			tm.put(chs[i],value+1);
		}
		StringBuilder sb=new StringBuilder();
		Set<Map.Entry<Character,Integer>> entry=tm.entrySet();
		Iterator<Map.Entry<Character,Integer>> it=entry.iterator();
		while(it.hasNext())
		{
			Map.Entry<Character,Integer> me=it.next();
			Character c=me.getKey();
			Integer count=me.getValue();
			sb.append(c+"("+count+")");
		}
		return sb.toString();
	}
}

33集合框架(Map擴展)

代碼示例1

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		HashMap<String,String> yure=new HashMap<String,String>();
		HashMap<String,String> jiuye=new HashMap<String,String>();
		HashMap<String,HashMap<String,String>> czbk=new HashMap<String,HashMap<String,String>>();
		yure.put("01","zhangsan1");
		yure.put("02","zhangsan2");
		jiuye.put("01","lisi1");
		jiuye.put("02","lisi2");
		czbk.put("jiuye",jiuye);
		czbk.put("yure",yure);
		Set<String> keys=czbk.keySet();
		Iterator<String> it=keys.iterator();
		while(it.hasNext())
		{
			String key1=it.next();
			HashMap<String,String> hs=czbk.get(key1);
			System.out.println(key1);
			Set<String> ks=hs.keySet();
			Iterator<String> iter=ks.iterator();
			while(iter.hasNext())
			{
				String key=iter.next();
				String value=hs.get(key);
				System.out.println(key+" "+value);
			}
		}
	}
}

代碼示例2

 import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
	ArrayList<Student> list=new ArrayList<Student>();
	list.add(new Student("01",23));
	list.add(new Student("02",22));
	list.add(new Student("03",33));
	list.add(new Student("04",33));
	HashMap<String,ArrayList<Student>> czbk=new HashMap<String,ArrayList<Student>>();
	czbk.put("jiuye",list);
	czbk.put("yure",list);
	Set<String> keys=czbk.keySet();
	Iterator<String> it=keys.iterator();
	while(it.hasNext())
	{
		String key=it.next();
		System.out.println(key);
		ArrayList<Student> value=czbk.get(key);
		for(int i=0;i<list.size();i++)
		{
			System.out.println(list.get(i).getName()+" "+list.get(i).getAge());
		}
	}
}
}
class Student
{
	private String name;
	private int age;
	public Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public String getName()
	{
		return this.name;
	}
	public int getAge()
	{
		return this.age;
	}
}

34 集合(Collections工具類)

  排序:Collections.sort(list,new StrLenCom());

最大值:Collections.max(list,new StrLenCom());

這版查找:Collections.binarySearchlist,”aaa”,new StrLenCom());

將集合中的元素全都替換成它:Collections.fill(list,”pp”)

集合中元素替換:Collections.replaceAll(list,”oldValue”,”newValue”)

集合中元素反轉:Collections.reverse(list)

強行逆轉指定比較器順序:Collections.reverseOrder(new StrLenCom());

強行逆轉實現Comparable接口的對象collection的自然順序:Collections.reverseOrder();

把元素隨機排放:Collections.shuffle(list)

元素換位置:Collections.swap(list,1,2)

將非同步的變成同步的:Collections.synchronizedListlist

示例代碼:

import java.util.*;
class  Test
{
	public static void main(String[] args) 
	{
		ArrayList<String> list=new ArrayList<String>();
		list.add("sddd");
		list.add("dkjld");
		list.add("dkdk");
		Collections.sort(list,new StrLenCom());
		String max=Collections.max(list,new StrLenCom());
		System.out.println(list);
		System.out.println(max);
}
}

class StrLenCom implements Comparator<String>
{
	public int compare(String s1,String s2)
	{
		int num= new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(num==0)
			return s1.compareTo(s2);
		return num;
	}
}      

35 集合(Arrays工具類)

Arrays:用於操作數組的工具類。

將數組變成字符串:Arrays.toStringarr)

將數組變成List集合:Arrays.asList(arr);(不可以使用集合的增刪方法)

*高級for循環

格式:

for(數據類型 變量名 被遍歷的集合(Collection)或者數組)

{

}

對集合進行遍歷。只能獲取集合元素。但是不能對集合進行操作。

迭代器除了遍歷,還可以進行remove集合中元素的動作。

如果是用ListIterator,還可以在遍歷過程中對集合進行增刪改查的動作。

傳統for和高級for有什麼區別呢?

高級for有一個侷限性。必須有被遍歷的目標。

建議在遍歷數組的時候,還是希望是用傳統for。因爲傳統for可以定義腳標。

*可變參數。

例如:

 public static void show(String str,int... arr)

{System.out.println(arr.length);}





---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity開發</a>、<a href="http://www.itheima.com"target="blank">.Net培訓</a>、期待與您交流! ----------------------



 




 



 

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章