滴水穿石-06集合
集合:長(zhǎng)度可變,存儲(chǔ)對(duì)象為引用類型
?
?
?1:?接口 Collection<E>
?
?
學(xué)習(xí)集合的流程大致是:首先學(xué)習(xí)構(gòu)造方法,然后看一些主要功能:增.刪.判.獲.長(zhǎng).其他.
a:增加功能(add() addAll())
package d6;import java.util.ArrayList; import java.util.Collection;public class CollectionTest {public static void main(String[] args) {Collection c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");////測(cè)試add方法System.out.println(c.toString());//------[Hello, world]--------// Collection c2 = new ArrayList(); c2.add("java");c2.add("javaSE"); c2.addAll(c);////測(cè)試addAll方法System.out.println(c2.toString());//-------[java, javaSE, Hello, world]-------// }} 1.0?b:刪除功能(remove() removeAll() clear())
public static void main(String[] args) {Collection c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.add("!");System.out.println(c.toString());// ------[Hello, world, !]--------// //// 測(cè)試remove方法c.remove("Hello");System.out.println(c.toString());// ------[world, !]--------// Collection c2 = new ArrayList();c2.add("java");c2.add("javaSE");c2.add("Hello");c2.add("world");c2.add("!");//// 測(cè)試removeAll方法System.out.println(c2.toString());// -------[java, javaSE, Hello, world, !]-------// c2.removeAll(c);System.out.println(c2.toString());// -------[java, javaSE, Hello]-------// //// 測(cè)試clear方法 c2.clear();System.out.println(c2.toString());// -------[]-------// } 1.0?c:判斷功能(contains() containsAll() isEmpty())
package d6;import java.util.ArrayList; import java.util.Collection;public class CollectionContains1 {public static void main(String[] args) {Collection c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象//// 測(cè)試isEmpty方法System.out.println(c.isEmpty());// ------true--------// c.add("Hello");//// 測(cè)試isEmpty方法System.out.println(c.isEmpty());// ------false--------// c.add("world");c.add("!");System.out.println(c.toString());// ------[Hello, world, !]--------// //// 測(cè)試contains方法System.out.println(c.contains("Hello"));// ------true--------// System.out.println(c.contains("Hlo"));// ------false--------// Collection c2 = new ArrayList();c2.add("java");c2.add("javaSE");c2.add("Hello");//// 測(cè)試contains方法 注意:包含所有元素才返回trueSystem.out.println(c2.contains(c));// -------false-------// } } 1.0?d:獲取功能(iterator())
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;public class collectionIterator1 {public static void main(String[] args) {//01 創(chuàng)建集合對(duì)象Collection c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象//02 創(chuàng)建添加對(duì)象 并添加到 集合對(duì)象String a ="Hello";String b ="world";c.add(a);c.add(b);//03 根據(jù)集合對(duì)象調(diào)用iterator對(duì)象Iterator i = c.iterator(); //a注意導(dǎo)包//04 循環(huán)遍歷iterator對(duì)象while (i.hasNext()) {System.out.println(i.next());}//-------Hello-------////-------world-------// }} 1.0?e:長(zhǎng)度功能(size())
package d6;import java.util.ArrayList; import java.util.Collection;public class CollectionSize1 {public static void main(String[] args) {Collection c = new ArrayList();c.add("java");c.add("javaSE");c.add("Hello");//// 測(cè)試size方法 System.out.println(c.size());// -------3-------// }} 1.0?f:交集功能(retainAll())?注意與ContrainAll()不同,如果此 collection 由于調(diào)用而發(fā)生更改,就返回true.為什么叫retain(保留)呢?因?yàn)榻患笤瓉?lái)的集合發(fā)生了變化,變成了交集后的值
package d6;import java.util.ArrayList; import java.util.Collection;public class CollectionRetainAll1 {public static void main(String[] args) {Collection c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象 c.add("Hello"); c.add("world");c.add("!");System.out.println(c.toString());// ------[Hello, world, !]--------// Collection c2 = new ArrayList();c2.add("java");c2.add("javaSE");c2.add("Hello");//// 測(cè)試retainAll方法 注意與ContrainAll不同,只要集合的值發(fā)生改變,就返回trueSystem.out.println(c2.retainAll(c));// -------true-------// System.out.println(c2.toString());// 注意此時(shí)c2的值// -------[Hello]-------// Collection c3 = new ArrayList();//// 測(cè)試retainAll方法 注意:與空集合求交集返回trueSystem.out.println(c2.retainAll(c3)); //// -------true-------// System.out.println(c2.toString());// 注意此時(shí)c2的值,沒(méi)有交集也是空// -------[]-------// c2.add("java");c2.add("javaSE");c2.add("Hello");c3.add("java11");System.out.println(c2.retainAll(c3));// -------true-------// System.out.println(c2.toString());// 注意此時(shí)c2的值,// -------[]-------// } } 1.0??g:轉(zhuǎn)化功能
package d6;import java.util.ArrayList; import java.util.Collection;public class CollectionChange1 {public static void main(String[] args) {// TODO Auto-generated method stubCollection c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象 c.add("Hello");c.add("world");c.add("!");Object [] a = c.toArray();for (int i = 0; i < a.length; i++) {System.out.print(a[i].toString());}//-----Helloworld!-------// }} 1.0?z:練習(xí):遍歷學(xué)生集合
package pojo;public class Student {public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";} } Student package d6;import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;import pojo.Student;public class CollectionIterator2 {public static void main(String[] args) {//01 創(chuàng)建集合對(duì)象Collection c = new ArrayList();//02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Student s3 = new Student("張三",13);Student s4 = new Student("李四",14);Student s5 = new Student("王五",15);Student s6 = new Student("趙六",16);c.add(s3);c.add(s4);c.add(s5);c.add(s6);//03 根據(jù)集合對(duì)象創(chuàng)建iterator對(duì)象Iterator it = c.iterator();//04 遍歷iterator對(duì)象while (it.hasNext()) {System.out.println(it.next().toString());}System.out.println("-------方法二--------");//03-02 轉(zhuǎn)化成數(shù)組Object [] sa = c.toArray();//04-02 遍歷數(shù)組for (int i = 0; i < sa.length; i++) {System.out.println(sa[i].toString());}//--------Student [姓名=張三, 年齡=13]------------////--------Student [姓名=李四, 年齡=14]------------////--------Student [姓名=王五, 年齡=15]------------////--------Student [姓名=趙六, 年齡=16]------------////---------------方法二--------------------////--------Student [姓名=張三, 年齡=13]------------////--------Student [姓名=李四, 年齡=14]------------////--------Student [姓名=王五, 年齡=15]------------////--------Student [姓名=趙六, 年齡=16]------------// }} Collection_test_011.1 List:有序;索引;可重復(fù);
?
a:增加功能(add() addAll()) ?可以在列表的指定位置插入指定元素
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.List;public class ListAdd1 {public static void main(String[] args) {List c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add(1,"world");////測(cè)試add方法System.out.println(c.toString());//------[Hello, world, !]--------// List c2 = new ArrayList(); c2.add("java");c2.add("javaSE"); c2.addAll(1,c);////測(cè)試addAll方法System.out.println(c2.toString());//-------[java, Hello, world, !, javaSE]-------// }} 1.0b:刪除功能(remove())?根據(jù)索引刪除元素,并返回被刪除元素
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.List;public class ListRemove1 {public static void main(String[] args) {List c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.add("!");System.out.println("原來(lái)的集合是: " +c.toString());// ------原來(lái)的集合是: [Hello, world, !]--------// //// 測(cè)試remove方法System.out.println("被刪除的元素是: " +c.remove(1));// ------被刪除的元素是: world--------// System.out.println("刪除后的結(jié)果是: " +c.toString());// ------刪除后的結(jié)果是: [Hello, !]--------// List c2 = new ArrayList();c2.add("java"); c2.add("Hello");c2.add("world");c2.add("!");c2.add("javaSE");//// 測(cè)試removeAll方法System.out.println("原來(lái)的集合是: " +c2.toString());// -------原來(lái)的集合是: [java, Hello, world, !, javaSE]-------// System.out.println("被刪除的元素是: "+c2.removeAll(c)); //注意這里返回true//--------被刪除的元素是: true------------// System.out.println("刪除后的結(jié)果是: "+c2.toString());// -------刪除后的結(jié)果是: [java, world, javaSE]-------// }} 1.0c:修改功能(set())
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.List;public class ListSet1 {public static void main(String[] args) {List c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add(1,"world");////測(cè)試set方法c.set(2,"!!!");System.out.println(c.toString());//------[Hello, world, !!!]--------// }} 1.0d:獲取功能(get())
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.List;public class ListGet1 {public static void main(String[] args) {List c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add(1,"world");////測(cè)試get方法 System.out.println(c.get(2));//------!--------// System.out.println(c.get(5));//------java.lang.IndexOutOfBoundsException:--------// }} 1.0e:查找功能(indexOf())
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.List;public class ListIndexOf1 {public static void main(String[] args) {List c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add(1,"world");////測(cè)試set方法System.out.println(c.indexOf("!!!"));//-------1--------// 注意這里是-1System.out.println(c.indexOf("!"+ ""));//------2--------// }} 1.0f:遍歷功能(listIterator())?
package d6;import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator;public class ListSet1 {public static void main(String[] args) {//01 創(chuàng)建集合對(duì)象List c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象//02 創(chuàng)建添加對(duì)象 并添加到 集合對(duì)象String a ="Hello";String b ="world";c.add(a);c.add(b);//03 根據(jù)集合對(duì)象調(diào)用iterator對(duì)象ListIterator i = c.listIterator(); //a注意導(dǎo)包//04 循環(huán)遍歷iterator對(duì)象while (i.hasNext()) {System.out.println(i.next());}//-------Hello-------////-------world-------////向前遍歷while (i.hasPrevious()) {System.out.println(i.previous());}//-------world-------////-------Hello-------// for (int h=0;h<c.size();h++) {System.out.println(c.get(h));}//-------Hello-------////-------world-------// } } 1.01.1.1 ArrayList
特點(diǎn):底層結(jié)構(gòu)是數(shù)組,查詢快,增刪慢,線程不安全,效率高
練習(xí):添加時(shí)去除重復(fù)元素(注意:Contains()底層是equals方法,所以要在Student類中,重寫(xiě)equals方法)
package pojo;public class Student {public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;} } Student package d6;import java.util.ArrayList; import java.util.Collection;import pojo.Student;public class ArrayListAdd2 {public static void main(String[] args) {ArrayList c = new ArrayList();// a:注意導(dǎo)包//b:new 子類對(duì)象// 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Student s3 = new Student("張三", 13);Student s4 = new Student("李四", 14);Student s5 = new Student("王五", 15);Student s55 = new Student("王五", 15);Student s6 = new Student("趙六", 16);if (!c.contains(s3)) {c.add(s3);}if (!c.contains(s4)) {c.add(s4);}if (!c.contains(s5)) {c.add(s5);}if (!c.contains(s55)) {c.add(s55);}if (!c.contains(s6)) {c.add(s6);}//// 測(cè)試add方法System.out.println(c.toString());// ------[Student [姓名=張三, 年齡=13], Student [姓名=李四, 年齡=14],//Student [姓名=王五, 年齡=15], Student [姓名=趙六, 年齡=16]]--------// }} addNoRepeat練習(xí)2:foreach 與集合的嵌套
package d6;import java.util.ArrayList; import java.util.Collection;import pojo.Student;public class ArrayListContainsArrayList {public static void main(String[] args) {ArrayList<ArrayList<Student>> c = new ArrayList<ArrayList<Student>>();// a:注意導(dǎo)包//b:new 子類對(duì)象 ArrayList<Student> s = new ArrayList<Student>(); ArrayList<Student> s1 = new ArrayList<Student>(); ArrayList<Student> s2 = new ArrayList<Student>();// 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Student s3 = new Student("張三", 13);Student s4 = new Student("李四", 14);Student s5 = new Student("王五", 25);Student s6 = new Student("趙六", 26);Student s7 = new Student("孫七", 77);s.add(s3); s.add(s4);s1.add(s5); s1.add(s6);s2.add(s7);c.add(s); c.add(s1); c.add(s2);//// 測(cè)試foreach嵌套for (ArrayList<Student> list : c) {for (Student student : list) {System.out.println(student.toString());}}//-------Student [姓名=張三, 年齡=13]----------////-------Student [姓名=李四, 年齡=14]----------////-------Student [姓名=王五, 年齡=25]----------////-------Student [姓名=趙六, 年齡=26]----------////-------Student [姓名=孫七, 年齡=77]----------// }} 1.01.1.2 Vector
特點(diǎn):底層結(jié)構(gòu)是數(shù)組,查詢快,增刪慢,線程安全,效率低
a:增加功能(addElement();被add()替代)
package d6;import java.util.Vector;public class VectorAdd1 {public static void main(String[] args) {Vector c = new Vector();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.addElement("!!");////測(cè)試addElement方法System.out.println(c.toString());//------[Hello, world, !!]--------// } } 1.0b:獲取功能(elementAt();被get()替代)
package d6;import java.util.Vector;public class VectorGet1 {public static void main(String[] args) {Vector c = new Vector();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.addElement("!!");////測(cè)試get方法System.out.println(c.get(1));//------world--------// ////測(cè)試elementAt方法System.out.println(c.elementAt(1));//------world--------// } } 1.0c:遍歷功能(Enumeration elements();被Iterator iterator()替代)
package d6;import java.util.Enumeration; import java.util.Vector;public class VectorEnumeration1 {public static void main(String[] args) {Vector c = new Vector();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.addElement("!!");////測(cè)試addElement方法System.out.println(c.toString());//------[Hello, world, !!]--------// Enumeration e = c.elements();while (e.hasMoreElements()) {System.out.println(e.nextElement());} //------Hello--------// //------world--------// //------!!--------// } } 1.01.1.3 LinkedList
特點(diǎn):底層結(jié)構(gòu)是鏈表,查詢慢,增刪快,線程不安全,效率高
a:增加功能(addFirst();addLast())
package d6;import java.util.LinkedList;public class LinkedListAdd1 {public static void main(String[] args) {LinkedList c = new LinkedList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("world");c.addFirst("Hello");c.addLast("!!!");////測(cè)試addFirst和addLast方法System.out.println(c.toString());//------[Hello, world]--------// }} 1.0b:獲取功能(getFirst();getLast())
package d6;import java.util.LinkedList;public class LinkedListGet1 {public static void main(String[] args) {LinkedList c = new LinkedList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add(1,"world");////測(cè)試get方法 System.out.println(c.getFirst());//------!--------// System.out.println(c.getLast());//--------------// }} 1.0c:刪除功能(removeFirst();removeLast() )
package d6;import java.util.LinkedList;public class ListRemove1 {public static void main(String[] args) {LinkedList c = new LinkedList();// a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("world");c.add("!");System.out.println("原來(lái)的集合是: " +c.toString());// ------原來(lái)的集合是: [Hello, world, !]--------// //// 測(cè)試remove方法System.out.println("被刪除的元素是: " +c.removeFirst());// ------被刪除的元素是: Hello--------// System.out.println("被刪除的元素是: " +c.removeLast());// ------被刪除的元素是: ! ---------// System.out.println("刪除后的結(jié)果是: " +c.toString());// ------刪除后的結(jié)果是: [world]--------// }} 1.0練習(xí):用LinkedList模擬棧數(shù)據(jù)結(jié)構(gòu)集合并測(cè)試 .(棧:先進(jìn)后出)
package dao.impl;import java.util.LinkedList;public class MyStack {private LinkedList link;public MyStack() {link = new LinkedList();}public void add(Object obj) {link.addFirst(obj);}public Object get() {return link.removeFirst();}public boolean isEmpty() {return link.isEmpty();} } MyStack package d6;import dao.impl.MyStack;public class LinkedList_Test1 {public static void main(String[] args) {MyStack m = new MyStack();m.add("1");m.add("2");m.add("3");m.add("4");while(!m.isEmpty()) {System.out.println(m.get());}//--------4---------////--------3---------////--------2---------////--------1---------// } } LinkedList_Test1?
1.2 Set:無(wú)序;唯一;
package d6;import java.util.HashSet; import java.util.Set;public class SetAdd1 {public static void main(String[] args) {Set<String> c = new HashSet<String>();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add("Hello");c.add("!");c.add("world");c.add("!");c.add("world");////測(cè)試Set屬性,無(wú)序和唯一System.out.println(c.toString());//------[!, world, Hello]--------// }} 1.01.2.1 HashSet
特點(diǎn):底層是哈希表.
唯一性粗淺理解:通過(guò)hashCode獲取到hash值進(jìn)行比較,如果相同進(jìn)一步比較地址值或者equal();如果地址值或者equal()相同,則表示相同,不在進(jìn)行添加操作
?練習(xí):
package pojo;public class Student {public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;} } Student package d6;import java.util.ArrayList; import java.util.HashSet;import pojo.Student;public class HashSetTest {public static void main(String[] args) {HashSet<Student> c = new HashSet<Student>();// a:注意導(dǎo)包//b:new 子類對(duì)象// 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中 ,注意需要重寫(xiě)Student中的hashCode和equal方法Student s3 = new Student("張三", 13);Student s4 = new Student("李四", 14);Student s5 = new Student("王五", 15);Student s55 = new Student("王五", 15);Student s6 = new Student("趙六", 16);c.add(s3);c.add(s4);c.add(s5);c.add(s55);c.add(s6);//// 測(cè)試add方法 ,注意HashSet是無(wú)序的System.out.println(c.toString());// ------[Student [姓名=王五, 年齡=15], Student [姓名=張三, 年齡=13], //Student [姓名=趙六, 年齡=16], Student [姓名=李四, 年齡=14]]--------// }} 1.01.2.1.1 LinkedHashSet:(有序;)
特點(diǎn):底層是哈希表(保證唯一)+鏈表(保證有序)組成
package pojo;public class Student {public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;} } Student package d6;import java.util.LinkedHashSet;import pojo.Student;public class LinkedHashSetTest {public static void main(String[] args) {LinkedHashSet<Student> c = new LinkedHashSet<Student>();// a:注意導(dǎo)包//b:new 子類對(duì)象// 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中 ,注意需要重寫(xiě)Student中的hashCode和equal方法Student s3 = new Student("張三", 13);Student s4 = new Student("李四", 14);Student s5 = new Student("王五", 15);Student s55 = new Student("王五", 15);Student s6 = new Student("趙六", 16);c.add(s3);c.add(s4);c.add(s5);c.add(s55);c.add(s6);//// 測(cè)試add方法 ,注意LinkedHashSet是有序的System.out.println(c.toString());// ------[Student [[Student [姓名=張三, 年齡=13], Student [姓名=李四, 年齡=14], //Student [姓名=王五, 年齡=15], Student [姓名=趙六, 年齡=16]]--------// }} 1.01.2.2 TreeSet
特點(diǎn):底層是紅黑二叉樹(shù)
a:自然排序
package d6;import java.util.ListIterator; import java.util.TreeSet;public class TreeSet1 {public static void main(String[] args) {//01 創(chuàng)建集合對(duì)象TreeSet<Integer> c= new TreeSet<Integer>();// a:注意導(dǎo)包//b:new 子類對(duì)象//02 創(chuàng)建添加對(duì)象 并添加到 集合對(duì)象 c.add(10);c.add(50);c.add(90);c.add(77);c.add(15);c.add(32);c.add(10);c.add(50); System.out.println(c.toString());//-------[10, 15, 32, 50, 77, 90]-------// } } 1.0練習(xí):根據(jù)學(xué)生的年齡排序
注意點(diǎn):1如要實(shí)現(xiàn)自然排序,需要實(shí)現(xiàn)Comparable接口;2:除了考慮到年齡排序的主要條件,還要考慮是否為同一學(xué)生的次要條件,避免年齡相同的兩個(gè)學(xué)生被過(guò)濾掉
package pojo;public class Student implements Comparable<Student>{public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}@Overridepublic int compareTo(Student o) {int num = this.getAge()-o.getAge();int num2=num==0?this.getName().compareTo(o.getName()):num;return num2;} } Student package d6;import java.util.TreeSet;import pojo.Student;public class TreeSet2 {//根據(jù)學(xué)生的年齡排序//注意點(diǎn):1如要實(shí)現(xiàn)自然排序,需要實(shí)現(xiàn)接口;//2:除了考慮到年齡排序的主要條件,還要考慮是否為同一學(xué)生的次要條件,避免年齡相同的兩個(gè)學(xué)生被過(guò)濾掉public static void main(String[] args) {// 01 創(chuàng)建集合對(duì)象TreeSet<Student> c = new TreeSet<Student>();// a:注意導(dǎo)包//b:new 子類對(duì)象 // 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Student s3 = new Student("張三", 13);Student s6 = new Student("趙六", 16);Student s4 = new Student("李四", 14);Student s5 = new Student("王五", 15);Student s55 = new Student("王小五", 15);Student s555 = new Student("王五", 15);c.add(s3);c.add(s6);c.add(s4);c.add(s5);c.add(s55);c.add(s555);System.out.println(c.toString());// -------[Student [姓名=張三, 年齡=13], Student [姓名=李四, 年齡=14],//Student [姓名=王五, 年齡=15], Student [姓名=王小五, 年齡=15], //Student [姓名=趙六, 年齡=16]]-------// } } TreeSet2b:比較器排序
注意點(diǎn):讓集合的構(gòu)造方法接收一個(gè)比較器接口的子類對(duì)象Comparator
練習(xí):按照學(xué)生的語(yǔ)文成績(jī)和數(shù)學(xué)成績(jī)之和進(jìn)行升序排序
package pojo;public class Score {@Overridepublic String toString() {return "Score [姓名=" + name + ", 語(yǔ)文=" + chinese + ", 數(shù)學(xué)=" + maths + ", 總成績(jī)="+sum()+"]";}private String name;private Integer chinese;private Integer maths;public Score(String name,int chinese,int maths) {this.name= name;this.chinese = chinese;this.maths=maths;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getChinese() {return chinese;}public void setChinese(Integer chinese) {this.chinese = chinese;}public Integer getMaths() {return maths;}public void setMaths(Integer maths) {this.maths = maths;}public int sum() {return this.chinese+this.maths; } } Score package dao.impl;import java.util.Comparator;import pojo.Score;public class ScoreCompare implements Comparator<Score> {@Overridepublic int compare(Score o1, Score o2) {//主要條件int num = o1.sum()-o2.sum();int num2=num==0?o1.getName().compareTo(o2.getName()):num;return num2;}} ScoreCompare package d6;import java.util.TreeSet;import dao.impl.ScoreCompare; import pojo.Score;public class TreeSet3 {//根據(jù)學(xué)生的總成績(jī)排序//注意點(diǎn):1如要實(shí)現(xiàn)比較器排序,需要實(shí)現(xiàn)創(chuàng)建一個(gè)比較;//2:除了考慮到年齡排序的主要條件,還要次要條件public static void main(String[] args) {// 01 創(chuàng)建集合對(duì)象TreeSet<Score> c = new TreeSet<Score>(new ScoreCompare());// a:注意導(dǎo)包//b:new 子類對(duì)象 // 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Score s3 = new Score("張三", 13,99);Score s6 = new Score("趙六", 60,60);Score s4 = new Score("李四", 90,0);Score s5 = new Score("王五", 75,60);Score s55 = new Score("王小五", 59,30);Score s555 = new Score("王五", 100,98);c.add(s3);c.add(s6);c.add(s4);c.add(s5);c.add(s55);c.add(s555);System.out.println(c.toString());// -------[Score [姓名=王小五, 語(yǔ)文=59, 數(shù)學(xué)=30, 總成績(jī)=89],//Score [姓名=李四, 語(yǔ)文=90, 數(shù)學(xué)=0, 總成績(jī)=90], //Score [姓名=張三, 語(yǔ)文=13, 數(shù)學(xué)=99, 總成績(jī)=112], //Score [姓名=趙六, 語(yǔ)文=60, 數(shù)學(xué)=60, 總成績(jī)=120], //Score [姓名=王五, 語(yǔ)文=75, 數(shù)學(xué)=60, 總成績(jī)=135], //Score [姓名=王五, 語(yǔ)文=100, 數(shù)學(xué)=98, 總成績(jī)=198]]-------// } } 1.0ps:還可以通過(guò)匿名對(duì)象簡(jiǎn)化
package pojo;public class Score {@Overridepublic String toString() {return "Score [姓名=" + name + ", 語(yǔ)文=" + chinese + ", 數(shù)學(xué)=" + maths + ", 總成績(jī)="+sum()+"]";}private String name;private Integer chinese;private Integer maths;public Score(String name,int chinese,int maths) {this.name= name;this.chinese = chinese;this.maths=maths;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getChinese() {return chinese;}public void setChinese(Integer chinese) {this.chinese = chinese;}public Integer getMaths() {return maths;}public void setMaths(Integer maths) {this.maths = maths;}public int sum() {return this.chinese+this.maths; } } Score package d6;import java.util.Comparator; import java.util.TreeSet;import pojo.Score;public class TreeSet4 {//根據(jù)學(xué)生的總成績(jī)排序//注意點(diǎn):1如要實(shí)現(xiàn)比較器排序,需要實(shí)現(xiàn)創(chuàng)建一個(gè)比較;//2:除了考慮到年齡排序的主要條件,還要次要條件public static void main(String[] args) {// 01 創(chuàng)建集合對(duì)象TreeSet<Score> c = new TreeSet<Score>( new Comparator<Score>(){public int compare(Score o1, Score o2) {//主要條件int num = o1.sum()-o2.sum();int num2=num==0?o1.getName().compareTo(o2.getName()):num;return num2;}}); // 02 創(chuàng)建學(xué)生對(duì)象 并添加到集合中Score s3 = new Score("張三", 13,99);Score s6 = new Score("趙六", 60,60);Score s4 = new Score("李四", 90,0);Score s5 = new Score("王五", 75,60);Score s55 = new Score("王小五", 59,30);Score s555 = new Score("王五", 100,98);c.add(s3);c.add(s6);c.add(s4);c.add(s5);c.add(s55);c.add(s555);System.out.println(c.toString());// -------[Score [姓名=王小五, 語(yǔ)文=59, 數(shù)學(xué)=30, 總成績(jī)=89],//Score [姓名=李四, 語(yǔ)文=90, 數(shù)學(xué)=0, 總成績(jī)=90], //Score [姓名=張三, 語(yǔ)文=13, 數(shù)學(xué)=99, 總成績(jī)=112], //Score [姓名=趙六, 語(yǔ)文=60, 數(shù)學(xué)=60, 總成績(jī)=120], //Score [姓名=王五, 語(yǔ)文=75, 數(shù)學(xué)=60, 總成績(jī)=135], //Score [姓名=王五, 語(yǔ)文=100, 數(shù)學(xué)=98, 總成績(jī)=198]]-------// } } 2.02:數(shù)據(jù)結(jié)構(gòu)
2.1 棧
2.2 隊(duì)列
2.3 數(shù)組
2.4 鏈表
2.5 哈希表
2.6 紅黑二叉樹(shù)
?
?3 泛型
?
是一種把類型明確的工作推遲到創(chuàng)建對(duì)象或調(diào)用方法時(shí)才去明確的特殊的參數(shù)化類型.
參數(shù)化類型:把類型當(dāng)做參數(shù)一樣傳遞.此處的數(shù)據(jù)類型是引用類型
格式:<參數(shù)類型>
優(yōu)點(diǎn): a:把運(yùn)行時(shí)的錯(cuò)誤提前到了編譯期間
?b:類型明確,避免了強(qiáng)制類型轉(zhuǎn)換和黃色警告線.
3.1 將ArrayList創(chuàng)建對(duì)象用泛型改進(jìn)
package d6;import java.util.ArrayList; import java.util.Iterator;public class ArrayList_generic {public static void main(String[] args) {// 測(cè)試泛型ArrayList<String> c = new ArrayList<String>();// a:注意導(dǎo)包//b:new 子類對(duì)象 c.add("Hello");c.add("World");c.add("!!!");Iterator<String> i = c.iterator();while (i.hasNext()) { System.out.println(i.next());} //-------Hello---------////-------World---------////-------!!!---------// }} 1.03.2 泛型類:泛型可以像參數(shù)一樣傳遞?
package dal;public class ObjectTool<T> {private T obj;public void setObj(T obj) {this.obj = obj; }public T getObj() {return this.obj;} } ObjectTool package d6;import dal.ObjectTool;public class ObjectTool_Test {public static void main(String[] args) {ObjectTool o = new ObjectTool();o.setObj("張三");System.out.println(o.getObj());//-------張三----------// o.setObj(111);System.out.println(o.getObj());//-------111----------//// 測(cè)試泛型類ObjectTool<String> o2 = new ObjectTool<String>();o2.setObj("張三");System.out.println(o2.getObj());//-------張三----------// }} 1.03.3 泛型方法
package dal;public class ObjectTool2 {//泛型方法public <T> void show(T t) {System.out.println(t);} } ObjectTool2 package d6;import dal.ObjectTool2;public class ObjectTool_Test2 {public static void main(String[] args) { ObjectTool2 o = new ObjectTool2();o.show("張三"); //-------張三----------// o.show(111); //-------111----------// }} 1.0?3.4 泛型接口
3.4.1 實(shí)現(xiàn)接口時(shí)可以確定類型
package dal;public interface Inter <T>{public abstract void show(T t); } Inter package dao.impl;import dal.Inter;public class Interimpl implements Inter<String>{@Overridepublic void show(String t) {// 第一種方式實(shí)現(xiàn)接口的時(shí)候已經(jīng)明確了類型System.out.println(t);}} Interimpl package d6;import dal.Inter; import dao.impl.Interimpl;public class InterImpl_test {public static void main(String[] args) {// 第一種方式實(shí)現(xiàn)接口的時(shí)候已經(jīng)明確了類型Inter<String> i = new Interimpl();//定義接口類型,通過(guò)具體的子類來(lái)實(shí)現(xiàn)i.show("張三");}} InterImpl_test3.4.2 實(shí)現(xiàn)接口時(shí)仍不能確定類型.較為常見(jiàn)
package dal;public interface Inter <T>{public abstract void show(T t); } Inter package dao.impl;import dal.Inter;public class Interimpl2<T> implements Inter<T>{@Overridepublic void show(T t) {// 第一種方式實(shí)現(xiàn)接口的時(shí)候已經(jīng)明確了類型System.out.println(t);}} Interimpl2 package d6;import dal.Inter; import dao.impl.Interimpl2;public class InterImpl_test2 {public static void main(String[] args) {// 第一種方式實(shí)現(xiàn)接口的時(shí)候已經(jīng)明確了類型Inter<String> i = new Interimpl2<String>();i.show("張三2");//------張三2----------// }} InterImpl_test2?3.5 泛型通配符
package d6;import java.util.ArrayList; import java.util.Collection;public class InterImpl_test3 {public static void main(String[] args) {Collection c = new ArrayList();// 01 寫(xiě)定了<Object>Collection<Object> c2 = new ArrayList<Object>();// Collection<Object> c2 = new ArrayList<Animal>(); ×// 02 ?通配符Collection<?> c3 = new ArrayList<Object>();Collection<?> c4 = new ArrayList<Animal>();Collection<?> c5 = new ArrayList<Dog>();// 03 ? extends T// Collection<? extends Animal> c6 = new ArrayList<Object>(); ×Collection<? extends Animal> c7 = new ArrayList<Animal>();Collection<? extends Animal> c8 = new ArrayList<Dog>();// 03 ? supper TCollection<? super Animal> c9 = new ArrayList<Object>(); Collection<? super Animal> c10 = new ArrayList<Animal>();//Collection<? super Animal> c11 = new ArrayList<Dog>(); × }}class Animal { }class Dog extends Animal { } 1.0?4.0 Map集合
?
鍵值對(duì)?。不能包含重復(fù)的鍵;每個(gè)鍵最多只能映射到一個(gè)值。
常用功能
a:增加功能(put() putAll())
特點(diǎn):如果key值不存在,則新增,返回值為null;?如果key值存在,則更新,返回值為被更新的Value
package d6;import java.util.HashMap; import java.util.Map;public class MapAdd1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();String r = m.put("張三", "1");System.out.println(r);// -------null-------// String r2 =m.put("張三", "001");System.out.println(r2);// -------null-------// m.put("李四", "002");m.put("王五", "003");//// 測(cè)試put方法System.out.println(m.toString());// -------{李四=002, 張三=001, 王五=003}-------// /** put方法* 1格式:V put(K key, V value)* 特點(diǎn):如果key值不存在,則新增,返回值為null;* 如果key值存在,則更新,返回值為,被更新的Value* */}} 1.0 package d6;import java.util.HashMap; import java.util.Map;public class MapPutAll1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();m.put("張三", "1"); m.put("張三", "001"); m.put("王五", "003");//// 測(cè)試put方法System.out.println(m.toString());// -------{張三=001, 王五=003}-------// Map<String, String> m1 = new HashMap<String, String>();m1.put("張三", "001");m1.put("李四", "002");m1.put("王五", "005");System.out.println(m1.toString());// -------{李四=002, 張三=001, 王五=005}-------// //// 測(cè)試put方法 m.putAll(m1);System.out.println(m.toString());// -------{李四=002, 張三=001, 王五=005}-------// /** putAll方法* 1格式:void putAll(Map<? extends K,? extends V> m)* 特點(diǎn):如果key值不存在,則新增, * 如果key值存在,則更新,則更新Value* */}} putAll() 1.0??b:刪除功能(remove() clear())
package d6;import java.util.HashMap; import java.util.Map;public class MapRemove1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();m.put("張三", "001");m.put("李四", "002");m.put("王五", "003");System.out.println(m.toString());// -------{李四=002, 張三=001, 王五=003}-------// 測(cè)試remove方法String r = m.remove("zhagnsan");System.out.println(r);// -------null-------// String r1 = m.remove("張三");System.out.println(r1);// -------001-------// System.out.println(m.toString());// -------{李四=002, 王五=003}-------// /** remove方法 1* 格式:V remove(Object key)* 特點(diǎn):如果映射關(guān)係不存在,返回值為null;* 如果映射關(guān)係存在,則移除映射關(guān)係,返回值為被移除的Value*/}} 1.0 package d6;import java.util.HashMap; import java.util.Map;public class MapClear1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();m.put("張三", "001");m.put("李四", "002");m.put("王五", "003");System.out.println(m.toString());// -------{李四=002, 張三=001, 王五=003}-------// m.clear();System.out.println(m.toString());// -------{}-------// /** clear方法 1* 格式:void clear()* 特點(diǎn):從集合中移除所有的映射關(guān)係*/}} 1.0??c:判斷功能(containsKey() containsValue() isEmpty())
package d6;import java.util.HashMap; import java.util.Map;public class MapContains {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();m.put("張三", "001");m.put("李四", "002");m.put("王五", "001");System.out.println(m.toString());// -------{李四=002, 張三=001, 王五=001}-------//// 測(cè)試containsKey方法System.out.println(m.containsKey("張三"));// -----true---------// System.out.println(m.containsKey("張三三"));// -----false--------//// 測(cè)試containsValue方法System.out.println(m.containsValue("001"));// -----true---------// System.out.println(m.containsValue("003"));// -----false---------// /** put方法 * 1格式:boolean containsKey(Object key);* boolean containsValue(Object value)* 特點(diǎn):存在true,不存在false*/}} 1.0 package d6;import java.util.HashMap; import java.util.Map;public class MapIsEmpty1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();System.out.println(m.isEmpty());// -------true-------// m.put("張三", "001"); m.put("王五", "003");System.out.println(m.isEmpty());// -------false-------// m.clear();System.out.println(m.isEmpty());// -------true-------// /** isEmpty方法* 1格式:boolean isEmpty()* 特點(diǎn): * */}} 1.0?d:長(zhǎng)度功能(size())
package d6;import java.util.HashMap; import java.util.Map;public class MapSize1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();System.out.println(m.size());// -------0-------// m.put("張三", "001"); m.put("王五", "003");System.out.println(m.size());// -------2-------// m.clear();System.out.println(m.size());// -------0-------// /** size方法* 1格式:int size()* 特點(diǎn): * */}} 1.0e:獲取功能(get() keySet() values() entrySet())
get(): ?根據(jù)鍵獲取值
keySet(); 獲取所有鍵
values(); 獲取所有值
entrySet(); ?獲取所有Map對(duì)象
package d6;import java.util.HashMap; import java.util.Map;public class MapGet1 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();m.put("張三", "001"); m.put("李四", "002");m.put("王五", "003"); 測(cè)試get方法System.out.println(m.get("zhangsan"));// -------null-------// System.out.println(m.get("張三"));// -------001-------// /** get方法* 1格式:V get(Object key)* 根據(jù)鍵找值 * 特點(diǎn):如果key值不存在,則返回null , * 如果key值存在,則返回Value* */}} 1.0 package d6;import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set;public class MapGet2 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();System.out.println(m.keySet()); // 獲取所有鍵// -------[]-------// System.out.println(m.values()); // 獲取所有值// -------[]-------// m.put("張三", "001");m.put("李四", "002");m.put("王五", "003"); 測(cè)試keySet方法Set<String> ks = m.keySet();System.out.println(ks);// -------[李四, 王五, 張三]-------// 測(cè)試values方法Collection<String> vls = m.values();System.out.println(m.values());// -------[002, 003, 001]-------// /** keySet方法 * 1格式:Set<K> keySet() 獲取所有鍵* 特點(diǎn):如果key不存在,則返回"" ,* 如果jet存在,則返回Set集合*//** values方法 * 1格式:Collection<V> values() 獲取所有值 * 特點(diǎn):如果value值不存在,則返回"" ,* 如果value值存在,則返回Collection集合*/}} 1.0 package d6;import java.util.HashMap; import java.util.Map; import java.util.Set;public class MapGet3 {public static void main(String[] args) {Map<String, String> m = new HashMap<String, String>();System.out.println(m.entrySet()); // 獲取所有map對(duì)象// -------[]-------// m.put("張三", "001");m.put("李四", "002");m.put("王五", "003"); 測(cè)試entrySet方法Set<Map.Entry<String, String>> es = m.entrySet();System.out.println(es);// -------[李四=002, 王五=003, 張三=001]-------// /** entrySet方法 * 1格式:Set<Map.Entry<K,V>> entrySet() 獲取所有鍵值對(duì)對(duì)象* 特點(diǎn):*/}} 1.0??z:練習(xí):遍歷學(xué)生集合
先獲取所有鍵,根據(jù)鍵找值;也可以直接獲取到map對(duì)象進(jìn)行遍歷
package d6;import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class MapTest1 {public static void main(String[] args) {Map<String, Student> m = new HashMap<String, Student>();Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);m.put("001", s1);m.put("002", s2);m.put("003", s3);// 方法 1 獲取所有鍵,根據(jù)鍵獲取值Set<String> keys = m.keySet();for (String key : keys) {Student s = m.get(key);System.out.println(key + "------" + s);} //-------001------Student [姓名=張三, 年齡=13]----------////-------002------Student [姓名=李四, 年齡=14]----------////-------003------Student [姓名=王五, 年齡=15]----------//// 方法2 獲取所有Map對(duì)象Set<Map.Entry<String, Student>> ents = m.entrySet();for (Map.Entry<String, Student> ent : ents) {String key = ent.getKey();Student st = ent.getValue();System.out.println(key + "------" + st);} //------001------Student [姓名=張三, 年齡=13]-----------////------002------Student [姓名=李四, 年齡=14]-----------////------003------Student [姓名=王五, 年齡=15]-----------// }} 1.04.1 HashMap:無(wú)序
底層是:哈希表
練習(xí):<Studetn,sring>
package pojo;public class Student implements Comparable<Student>{public Student () {}public Student (String name ,int age) {this.name=name;this.age=age;}private String name;private int 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;}@Overridepublic String toString() {return "Student [姓名=" + name + ", 年齡=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}@Overridepublic int compareTo(Student o) {int num = this.getAge()-o.getAge();int num2=num==0?this.getName().compareTo(o.getName()):num;return num2;} } Student package d6;import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class HashMapTest1 {public static void main(String[] args) {HashMap<Student,String> m = new HashMap<Student,String>() ;Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);Student s4 = new Student("張三", 13);m.put( s1,"001");m.put( s2,"002");m.put( s3,"003");m.put( s4,"004");// 方法2 獲取所有Map對(duì)象Set<Map.Entry<Student,String>> ents = m.entrySet();for (Map.Entry<Student,String> ent : ents) {Student key = ent.getKey();String st = ent.getValue();System.out.println(key + "------" + st);} //-----Student [姓名=王五, 年齡=15]------003-----------////-----Student [姓名=張三, 年齡=13]------004-----------////-----Student [姓名=李四, 年齡=14]------002-----------////注意:若要實(shí)現(xiàn)Student的唯一需要重寫(xiě)hashCode 和equals方法 }} 1.0?4.1.1 LinkedHashMap 唯一;有序
底層是:哈希表 + 鏈表
package d6;import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map;public class LinkedHashMapTest1 {public static void main(String[] args) { Map<String, String> m = new HashMap<String, String>(); m.put("張三", "001"); m.put("李四", "002");m.put("王五", "003");System.out.println(m.toString()); // -------{李四=002, 張三=001, 王五=003}-------// LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>();lhm.put("張三", "001"); lhm.put("李四", "002");lhm.put("王五", "003");System.out.println(lhm.toString());// -------{張三=001, 李四=002, 王五=003}-------////通過(guò)對(duì)比說(shuō)明其是有序的 }} 1.04.2 TreeMap?
底層是:紅黑樹(shù)
package d6;import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap;import pojo.Student;public class TreeMapTest1 {public static void main(String[] args) { TreeMap<Student, String> m = new TreeMap<Student, String>(); Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 16);Student s3 = new Student("王五", 15);Student s4 = new Student("張三", 13);m.put( s1,"001");m.put( s2,"002");m.put( s3,"003");m.put( s4,"004");// 方法2 獲取所有Map對(duì)象Set<Map.Entry<Student,String>> ents = m.entrySet();for (Map.Entry<Student,String> ent : ents) {Student key = ent.getKey();String st = ent.getValue();System.out.println(key + "------" + st);} //-----Student [姓名=張三, 年齡=13]------004----------////-----Student [姓名=王五, 年齡=15]------003----------////-----Student [姓名=李四, 年齡=16]------002----------//// Student中實(shí)現(xiàn)接口implements Comparable<Student> }} 1.0?練習(xí):判斷一個(gè)字符串中字符出現(xiàn)的次數(shù)
package d6;import java.util.Map; import java.util.Set; import java.util.TreeMap;public class CharCount {public static void main(String[] args) {// 計(jì)算一個(gè)字符串中元素出現(xiàn)個(gè)此處并按順序給出//“asdfsfdgj” a(1);d(2);f(2);g(1);j(1);s(2)String str = "asdfsfdgj";//01 將字符串轉(zhuǎn)化為數(shù)組char[] chsrs = str.toCharArray();//02 定義Map對(duì)象TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();//03 循環(huán)遍歷數(shù)組for (char c : chsrs) {//04 如果TreeMap中存在則+1;如果不存在就添加if (tm.get(c)!=null) {int value = tm.get(c) +1;tm.put(c, value);}else { tm.put(c, 1);} }//04 循環(huán)遍歷MapStringBuilder sb = new StringBuilder();Set<Map.Entry<Character,Integer>> ets = tm.entrySet();for (Map.Entry<Character,Integer> et : ets) {sb.append(et.getKey()+"(");sb.append(et.getValue()+")");sb.append(";");}String result =sb.toString().substring(0,sb.toString().lastIndexOf(";"));System.out.println(result);//---------a(1);d(2);f(2);g(1);j(1);s(2)----------// }} 1.05 集合的嵌套練習(xí)
5.1 HashMap<HashMap>
package d6;import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class CollectionMapTest1 {public static void main(String[] args) {//創(chuàng)建對(duì)象---開(kāi)始HashMap<String,HashMap<Integer,Student>> hh = new HashMap<String,HashMap<Integer,Student>>();HashMap<Integer,Student> hsAnYang = new HashMap<Integer,Student>();HashMap<Integer,Student> hsZhengZhou = new HashMap<Integer,Student>();Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);Student s4 = new Student("趙六", 16);//創(chuàng)建對(duì)象---結(jié)束//添加對(duì)象---開(kāi)始hsAnYang.put(2, s2);hsAnYang.put(1, s1); hsZhengZhou.put(1, s3);hsZhengZhou.put(2, s4);hh.put("鄭州", hsZhengZhou);hh.put("安陽(yáng)", hsAnYang); //添加對(duì)象---結(jié)束 //遍歷對(duì)象---開(kāi)始Set<String> hhKeys = hh.keySet();for (String hhKey : hhKeys) {HashMap<Integer,Student> hhValues = hh.get(hhKey);Set<Map.Entry<Integer,Student>> hsStudents = hhValues.entrySet();for (Map.Entry<Integer, Student> entry : hsStudents) {String studentNO = entry.getKey().toString();Student StudentInfo = entry.getValue();System.out.println("地區(qū): "+hhKey+"|||||||"+"學(xué)號(hào): "+studentNO+"--詳細(xì)信息: "+StudentInfo);}}//遍歷對(duì)象---結(jié)束/* 地區(qū): 安陽(yáng)|||||||學(xué)號(hào): 1--詳細(xì)信息: Student [姓名=張三, 年齡=13]地區(qū): 安陽(yáng)|||||||學(xué)號(hào): 2--詳細(xì)信息: Student [姓名=李四, 年齡=14]地區(qū): 鄭州|||||||學(xué)號(hào): 1--詳細(xì)信息: Student [姓名=王五, 年齡=15]地區(qū): 鄭州|||||||學(xué)號(hào): 2--詳細(xì)信息: Student [姓名=趙六, 年齡=16]* */} } 1.05.2?HashMap<ArrayList>
package d6;import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class CollectionMapTest2 {public static void main(String[] args) {//創(chuàng)建對(duì)象---開(kāi)始HashMap<String,ArrayList<Student>> hh = new HashMap<String,ArrayList<Student>>();ArrayList<Student> hsAnYang = new ArrayList<Student>();ArrayList<Student> hsZhengZhou = new ArrayList<Student>();Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);Student s4 = new Student("趙六", 16);//創(chuàng)建對(duì)象---結(jié)束//添加對(duì)象---開(kāi)始 hsAnYang.add(s2);hsAnYang.add(s1); hsZhengZhou.add(s3);hsZhengZhou.add(s4);hh.put("鄭州", hsZhengZhou);hh.put("安陽(yáng)", hsAnYang); //添加對(duì)象---結(jié)束 //遍歷對(duì)象---開(kāi)始Set<String> hhKeys = hh.keySet();for (String hhKey : hhKeys) {ArrayList<Student> hhValues = hh.get(hhKey); for (Student student : hhValues) { System.out.println("地區(qū): "+hhKey+"|||||||--詳細(xì)信息: "+student);}}//遍歷對(duì)象---結(jié)束/* 地區(qū): 安陽(yáng)|||||||--詳細(xì)信息: Student [姓名=李四, 年齡=14] 地區(qū): 安陽(yáng)|||||||--詳細(xì)信息: Student [姓名=張三, 年齡=13] 地區(qū): 鄭州|||||||--詳細(xì)信息: Student [姓名=王五, 年齡=15] 地區(qū): 鄭州|||||||--詳細(xì)信息: Student [姓名=趙六, 年齡=16]* */} } 1.0?5.3?Array<ListHashMap>
package d6;import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class CollectionMapTest3 {public static void main(String[] args) {//創(chuàng)建對(duì)象---開(kāi)始ArrayList<HashMap<Integer,Student>> hh = new ArrayList<HashMap<Integer,Student>>();HashMap<Integer,Student> hsAnYang = new HashMap<Integer,Student>();HashMap<Integer,Student> hsZhengZhou = new HashMap<Integer,Student>();Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);Student s4 = new Student("趙六", 16);//創(chuàng)建對(duì)象---結(jié)束//添加對(duì)象---開(kāi)始hsAnYang.put(2, s2);hsAnYang.put(1, s1); hsZhengZhou.put(1, s3);hsZhengZhou.put(2, s4);hh.add(hsZhengZhou);hh.add(hsAnYang); //添加對(duì)象---結(jié)束 //遍歷對(duì)象---開(kāi)始 for (HashMap<Integer,Student> list : hh) { Set<Map.Entry<Integer,Student>> hsStudents = list.entrySet();for (Map.Entry<Integer, Student> entry : hsStudents) {String studentNO = entry.getKey().toString();Student StudentInfo = entry.getValue();System.out.println("學(xué)號(hào): "+studentNO+"--詳細(xì)信息: "+StudentInfo);}}//遍歷對(duì)象---結(jié)束/* 學(xué)號(hào): 1--詳細(xì)信息: Student [姓名=王五, 年齡=15] 學(xué)號(hào): 2--詳細(xì)信息: Student [姓名=趙六, 年齡=16] 學(xué)號(hào): 1--詳細(xì)信息: Student [姓名=張三, 年齡=13] 學(xué)號(hào): 2--詳細(xì)信息: Student [姓名=李四, 年齡=14]* */} } 1.0?5.4 HashMap<HashMap<HashMap>>
package d6;import java.util.HashMap; import java.util.Map; import java.util.Set;import pojo.Student;public class CollectionMapTest4 {public static void main(String[] args) {// 創(chuàng)建對(duì)象---開(kāi)始HashMap<String, HashMap<String, HashMap<Integer, Student>>> hhh = new HashMap<String, HashMap<String, HashMap<Integer, Student>>>();HashMap<String, HashMap<Integer, Student>> hh = new HashMap<String, HashMap<Integer, Student>>();HashMap<String, HashMap<Integer, Student>> hh2 = new HashMap<String, HashMap<Integer, Student>>();HashMap<Integer, Student> hsAnYang = new HashMap<Integer, Student>();HashMap<Integer, Student> hsZhengZhou = new HashMap<Integer, Student>();HashMap<Integer, Student> hsHanDan = new HashMap<Integer, Student>();HashMap<Integer, Student> hsShiJiaZhuang = new HashMap<Integer, Student>();Student s1 = new Student("張三", 13);Student s2 = new Student("李四", 14);Student s3 = new Student("王五", 15);Student s4 = new Student("趙六", 16); Student s11 = new Student("張三三", 13);Student s22 = new Student("李四四", 14);Student s33 = new Student("王五五", 15);Student s44 = new Student("趙六六", 16);// 創(chuàng)建對(duì)象---結(jié)束// 添加對(duì)象---開(kāi)始hsAnYang.put(2, s2);hsAnYang.put(1, s1);hsZhengZhou.put(1, s3);hsZhengZhou.put(2, s4);hsHanDan.put(2, s22);hsHanDan.put(1, s11);hsShiJiaZhuang.put(1, s33);hsShiJiaZhuang.put(2, s44);hh.put("鄭州", hsZhengZhou);hh.put("安陽(yáng)", hsAnYang); hh2.put("石家莊", hsShiJiaZhuang);hh2.put("邯鄲", hsHanDan); hhh.put("河南", hh);hhh.put("河北", hh2);// 添加對(duì)象---結(jié)束// 遍歷對(duì)象---開(kāi)始Set<Map.Entry<String, HashMap<String, HashMap<Integer, Student>>>> hhhEntrys = hhh.entrySet();for (Map.Entry<String, HashMap<String, HashMap<Integer, Student>>> hhhEntry : hhhEntrys) {//System.out.println(hhhEntry);String hhKeys = hhhEntry.getKey();HashMap<String, HashMap<Integer, Student>> hhValues = hhhEntry.getValue();//System.out.println(hhValues);Set<Map.Entry<String, HashMap<Integer, Student>>> hhEntrys = hhValues.entrySet();for (Map.Entry<String, HashMap<Integer, Student>> hhEntry : hhEntrys) {String hKeys = hhEntry.getKey();HashMap<Integer, Student> hValues = hhEntry.getValue();Set<Map.Entry<Integer, Student>> hEntrys = hValues.entrySet();for (Map.Entry<Integer, Student> hEntry : hEntrys) {Integer sNO = hEntry.getKey();Student sInfo = hEntry.getValue();System.out.println("省: "+hhKeys+"--市: "+hKeys+"---學(xué)號(hào): "+sNO+"---學(xué)生詳細(xì)信息: "+sInfo);} }}// 遍歷對(duì)象---結(jié)束/* 省: 河南--市: 安陽(yáng)---學(xué)號(hào): 1---學(xué)生詳細(xì)信息: Student [姓名=張三, 年齡=13] 省: 河南--市: 安陽(yáng)---學(xué)號(hào): 2---學(xué)生詳細(xì)信息: Student [姓名=李四, 年齡=14] 省: 河南--市: 鄭州---學(xué)號(hào): 1---學(xué)生詳細(xì)信息: Student [姓名=王五, 年齡=15] 省: 河南--市: 鄭州---學(xué)號(hào): 2---學(xué)生詳細(xì)信息: Student [姓名=趙六, 年齡=16] 省: 河北--市: 邯鄲---學(xué)號(hào): 1---學(xué)生詳細(xì)信息: Student [姓名=張三三, 年齡=13] 省: 河北--市: 邯鄲---學(xué)號(hào): 2---學(xué)生詳細(xì)信息: Student [姓名=李四四, 年齡=14] 省: 河北--市: 石家莊---學(xué)號(hào): 1---學(xué)生詳細(xì)信息: Student [姓名=王五五, 年齡=15] 省: 河北--市: 石家莊---學(xué)號(hào): 2---學(xué)生詳細(xì)信息: Student [姓名=趙六六, 年齡=16]*/} } 1.0?6 Collections
?
?6.1 常用方法
sort();?根據(jù)元素的自然順序 對(duì)指定列表按升序進(jìn)行排序。當(dāng)然也可以根據(jù)比較器進(jìn)行排序
max() ; 返回最大值
min(); ?返回最小值
binarySearch(): 二分查找 ;如果存在返回索引值,如果不存在返回-(集合長(zhǎng)度+1)
reverse(); 集合反轉(zhuǎn)
shuffle(); 隨機(jī)置換
package d6;import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;public class CollectionsTest {public static void main(String[] args) {List c = new ArrayList();//a:注意導(dǎo)包//b:new 子類對(duì)象c.add(20);c.add(50);c.add(30);c.add(10);c.add(40);測(cè)試sort方法 默認(rèn)自然排序 Collections.sort(c);System.out.println(c.toString());//------[10, 20, 30, 40, 50]--------// System.out.println(Collections.max(c));//------50--------// System.out.println(Collections.min(c));//------10--------// System.out.println(Collections.binarySearch(c,30));//------2--------// System.out.println(Collections.binarySearch(c,300));//-------6--------// Collections.reverse(c); System.out.println(c.toString());//------[50, 40, 30, 20, 10]--------// Collections.shuffle(c);System.out.println(c.toString());//------[50, 20, 10, 40, 30]--------// }} 1.0?練習(xí):斗地主
package d6;import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet;public class PlayTest {public static void main(String[] args) {//創(chuàng)建一個(gè)表,用于記錄每張牌的大小HashMap<Integer,String> ruleMap = new HashMap<Integer,String>();//創(chuàng)建一個(gè)牌盒(牌盒里其實(shí)就是54個(gè)數(shù)值,通過(guò)規(guī)則與之對(duì)應(yīng))ArrayList<Integer> pokersList = new ArrayList(); for (int i = 0; i < 54; i++) {pokersList.add(i);}//創(chuàng)建花色數(shù)組String [] colorArray = {"?","?","?","?"};//創(chuàng)建點(diǎn)數(shù)數(shù)組String [] pointArray = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};//創(chuàng)建撲克牌并放入牌盒,同時(shí)將大小規(guī)則記錄在ruleMap表中int index = 0;for (int i = 0; i < pointArray.length; i++) {for (String colorStr : colorArray) {String poker = colorStr+pointArray[i] +" ";ruleMap.put(index, poker);index++;}}ruleMap.put(index, "小王");index++;ruleMap.put(index, "大王");//洗牌 Collections.shuffle(pokersList);//創(chuàng)建玩家,發(fā)牌ArrayList<Integer> zhangSan = new ArrayList<Integer>();ArrayList<Integer> liSi = new ArrayList<Integer>();ArrayList<Integer> wangWu = new ArrayList<Integer>();ArrayList<Integer> diPai = new ArrayList<Integer>();for (int i = 0; i < pokersList.size(); i++) {if (i>=pokersList.size()-3) {diPai.add(pokersList.get(i));}else if (i%3==0) {zhangSan.add(pokersList.get(i));}else if (i%3==1) {liSi.add(pokersList.get(i));}else if (i%3==2) {wangWu.add(pokersList.get(i));}}//看牌:把每位玩家的TreeSet中的值通過(guò)規(guī)則表匹配排序輸出lookPoker("張三",zhangSan,ruleMap);lookPoker("李四",liSi,ruleMap);lookPoker("王五",wangWu,ruleMap);lookPoker("底牌",diPai,ruleMap);}private static void lookPoker(String name, ArrayList<Integer> player,HashMap<Integer,String> ruleMap) {//拿到每位玩家的牌以后排序 Collections.sort(player);//排完序后輸出StringBuilder sb = new StringBuilder();for (Integer piont : player) {sb.append(ruleMap.get(piont));}System.out.println(name+": "+sb.toString());} /* 張三: ?3 ?3 ?4 ?4 ?4 ?5 ?7 ?8 ?9 ?9 ?10 ?J ?K ?A ?A ?2 ?2 李四: ?3 ?3 ?4 ?5 ?5 ?5 ?6 ?6 ?8 ?8 ?9 ?10 ?10 ?J ?Q ?Q ?K 王五: ?6 ?6 ?7 ?7 ?7 ?8 ?9 ?10 ?J ?J ?Q ?Q ?K ?A ?2 小王大王 底牌: ?K ?A ?2 * */ } 1.01.0版在看牌排序的時(shí)候用的是Collections的sort()方法,也可以通過(guò)TreeSet完成自動(dòng)排序
package d6;import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet;public class PlayTest2 {public static void main(String[] args) {//創(chuàng)建一個(gè)表,用于記錄每張牌的大小HashMap<Integer,String> ruleMap = new HashMap<Integer,String>();//創(chuàng)建一個(gè)牌盒(牌盒里其實(shí)就是54個(gè)數(shù)值,通過(guò)規(guī)則與之對(duì)應(yīng))ArrayList<Integer> pokersList = new ArrayList(); for (int i = 0; i < 54; i++) {pokersList.add(i);}//創(chuàng)建花色數(shù)組String [] colorArray = {"?","?","?","?"};//創(chuàng)建點(diǎn)數(shù)數(shù)組String [] pointArray = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};//創(chuàng)建撲克牌并放入牌盒,同時(shí)將大小規(guī)則記錄在ruleMap表中int index = 0;for (int i = 0; i < pointArray.length; i++) {for (String colorStr : colorArray) {String poker = colorStr+pointArray[i] +" ";ruleMap.put(index, poker);index++;}}ruleMap.put(index, "小王");index++;ruleMap.put(index, "大王");//洗牌 Collections.shuffle(pokersList);//創(chuàng)建玩家,發(fā)牌TreeSet<Integer> zhangSan = new TreeSet<Integer>();TreeSet<Integer> liSi = new TreeSet<Integer>();TreeSet<Integer> wangWu = new TreeSet<Integer>();TreeSet<Integer> diPai = new TreeSet<Integer>();for (int i = 0; i < pokersList.size(); i++) {if (i>=pokersList.size()-3) {diPai.add(pokersList.get(i));}else if (i%3==0) {zhangSan.add(pokersList.get(i));}else if (i%3==1) {liSi.add(pokersList.get(i));}else if (i%3==2) {wangWu.add(pokersList.get(i));}}//看牌:把每位玩家的TreeSet中的值通過(guò)規(guī)則表匹配排序輸出lookPoker("張三",zhangSan,ruleMap);lookPoker("李四",liSi,ruleMap);lookPoker("王五",wangWu,ruleMap);lookPoker("底牌",diPai,ruleMap);}private static void lookPoker(String name, TreeSet<Integer> player,HashMap<Integer,String> ruleMap) {StringBuilder sb = new StringBuilder();for (Integer piont : player) {sb.append(ruleMap.get(piont));}System.out.println(name+": "+sb.toString());} /* 張三: ?3 ?3 ?4 ?6 ?6 ?7 ?9 ?10 ?10 ?J ?J ?J ?K ?A ?2 ?2 小王 李四: ?4 ?4 ?5 ?5 ?5 ?6 ?6 ?7 ?8 ?8 ?8 ?9 ?10 ?10 ?Q ?K ?A 王五: ?3 ?5 ?7 ?7 ?8 ?9 ?9 ?J ?Q ?Q ?Q ?K ?K ?A ?A ?2 ?2 底牌: ?3 ?4 大王* */ } 2.0?
轉(zhuǎn)載于:https://www.cnblogs.com/YK2012/p/8319852.html
總結(jié)
- 上一篇: 装修施工队可以在哪些平台接活?
- 下一篇: 雷士照明带风扇的吊灯轴承是弯的吗?雷士照