泛型,TreeMap,HashMap
阿新 • • 發佈:2018-12-17
//泛型 //在類上使用泛型,要求在使用集合時必須制定泛型 class Student{ private Object obj; public Student() { } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } } //使用泛型後 //E:代表任何一種資料型別,但是<>中不一定寫E,任意的字母都可以 //<大寫字母>相當於宣告泛型 //在類上確定的泛型可以直接在方法上使用 class Student1<E>{ private E obj; public Student1() { } public E getObj() { return obj; } public void setObj(E obj) { this.obj = obj; } } class Tool{ private String name; public Tool() { super(); // TODO Auto-generated constructor stub } public Tool(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Iphone extends Tool{ public Iphone(String name) { super(name); } } class Computer extends Tool{ public Computer(String name) { super(name); } } public class Demo1 { public static void main(String[] args) { //---------------使用泛型前------------ Iphone i=new Iphone("huawei"); Computer c=new Computer("lianxiang"); Student s1=new Student(); s1.setObj(i);//相當於obj=new Iphone("huawei");多型 //獲取工具 Object obj=s1.getObj();//obj=new Iphone("huawei");多型 //向下轉型 Iphone i2=(Iphone)obj;//向下轉型相當於i2=new Iphone("huawei"),也就是,先向上轉型,再向下轉型,還是那個物件不變 Computer c2=(Computer)obj;//c2=new Iphone("huawei");這是一個錯誤,是執行時錯誤 //---------------使用泛型後------------ Iphone i4=new Iphone("huawei"); Computer c4=new Computer("lianxiang"); Student1<Computer> s4=new Student1<>(); // s4.setObj(i4);當泛型指定為Computer,再往裡面放其他型別就會有編譯錯誤 s4.setObj(c4);//通過設定泛型,引數的型別已經確定了 Computer c3=s4.getObj(); } }
import java.util.*; /* * 在方法上使用泛型 */ class Dog<E>{ //1當方法上的泛型與類的泛型保持一致 public E show(E e) { return e; } //2方法擁有屬於自己的泛型 /* * 注意:泛型在使用之前一定要進行宣告 * 宣告的方式:在修飾符的後面新增<大寫字母> * 作用:讓方法與方法內部的泛型保持一致 */ public <F> void play(F f) { ArrayList<F> list=null; } //3靜態方法上使用泛型 //靜態方法無法使用類上的泛型,類上的泛型必須通過建立物件使用 //靜態方法想使用泛型要自己獨立使用 public static <W> void song(W a){ } } public class Demo3 { public static void main(String[] args) { //1方法上的泛型與類的泛型保持一致 Dog<String> dog=new Dog<>(); dog.show("haha"); //2 dog.play("haha"); //3 Dog.<String>song("haha"); } }
/* * 泛型應用於介面上 */ public class Demo4 { public static void main(String[] args) { Cat cat=new Cat(); cat.show("haha"); Pig<String> pig=new Pig<>(); pig.show("haha"); } } interface Inter<E>{ public abstract void show(E e); } //介面上使用了泛型 //子類使用泛型的情況 //第一種情況:介面有泛型,子類沒有遵守對應的泛型,而是指定了具體的型別,使這個未知型別不再有效 /*在實現的介面位置必須指定一個具體的泛型 * * 方法使用泛型的情況: * 1如果是重寫的方法,泛型與介面一致 * 2如果是子類自己的方法,可以與介面一致,也可以有自己的泛型 */ class Cat implements Inter<String>{ //重新父介面中的方法 public void show(String e) { System.out.println("show"); } //自己的方法 public <F> void play(F f) { } } //第二種情況:介面有泛型,子類遵守了對應的泛型 class Pig<E> implements Inter{//????????????這個程式碼可能不太對 @Override public void show(Object e) { System.out.println("haha"); } }
import java.util.*;
/*
* 輸出為{}是map
* 輸出為[]是list
* Map:介面
* HashMap:底層是雜湊表,執行緒不安全的
* TreeMap:底層是二叉樹,執行緒不安全的
*
* Map:本身是介面,儲存的是鍵值對,一個元素就是一個鍵(key)值(value)對,key必須是唯一的,值隨意,即可以重複
* Collection:直接儲存的是值
*
*/
public class Demo7 {
public static void main(String[] args) {
//這裡是同時給鍵值指定泛型
//一般充當key的是字串或者是包裝類
Map<String,String> map=new HashMap<String,String>();
//介紹Map介面的方法
//1.增加
//V put(K key,V value) 增加一個鍵值對
map.put("01", "java");//增加一個鍵值對
map.put("02", "php");
map.put("03", "ios");
//System.out.println(map.put("03", "ios"));
//put方法的返回值:
//如果當前的key之前沒有新增過,返回null,如果當前的key之前已經新增過,返回之前的值
map.put("03", "BigData");//鍵相同的話。後面的鍵值對會覆蓋前面的鍵值對
System.out.println(map);//輸出:{01=java, 02=php, 03=BigData}
//void putAll(Map<? extends K,? extends V> map) 增加多個
//2.刪除
//V remove(Object key) 根據key刪除元素,該方法返回被刪掉的元素
// System.out.println(map.remove("01"));
// System.out.println(map);
//void clear() 刪除全部
// map.clear();
//3.獲取
//V get(Object key) 根據key查詢元素
System.out.println(map.get("01"));
//int size() 獲取鍵值對的個數
System.out.println(map.size());
//Set<K> keySet() 遍歷方法一
//Set<Map.Entry<K,V>> entrySet() 遍歷方法二
//4.常用的判斷
//boolean isEmpty()
System.out.println(map.isEmpty());
//boolean containsKey(K key) 是否包含當前的key
System.out.println(map.containsKey("01"));
//boolean containsValue(V value) 是否包含當前的value
System.out.println(map.containsValue("php"));
}
}
import java.util.*;
import java.util.Map.*;
//Set<K> keySet() 遍歷方法一
//第一種
// 原理:先得到所有的key放到一個set中,利用set的迭代器進行遍歷,得到key,再利用key獲取value
//
//方法二
//Set<Map.Entry<K,V>> entrySet()遍歷
//原理:先得到所有的entry,放入一個Set中,利用Set的迭代器進行遍歷得到entry實體,再利用entry的方法獲取key和value
//Map.Entry:其實Entry是Map的一個內部介面(可以參考內部類)
//相當於Map裡的每一個鍵值對都是一個Entry,Map是由Entry組成的
//Map.Entry,Entry物件僅在迭代時有效,在迭代的時候可以直接通過這個物件.setValue()去修改Map中的值
//Entry的方法:getValue() getKey() setValue()
public class Demo8 {
public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>();
map.put("01", "java");//增加一個鍵值對
map.put("02", "php");
map.put("03", "ios");
map.put("03", "BigData");
System.out.println(map);
//使用KeySet實現遍歷
//獲取裝著key的Set
Set set1=map.keySet();
//遍歷Set,獲取多有的Key
Iterator<String>it1 =set1.iterator();
while(it1.hasNext()) {
String key=it1.next();
System.out.println(key+" "+map.get(key));
}
//使用entrySet實現遍歷
Set<Map.Entry<String,String>> set2=map.entrySet();
//遍歷set,獲取所有的entry
Iterator<Map.Entry<String,String>> it2=set2.iterator();
while(it2.hasNext()) {
Map.Entry<String, String> entry=it2.next();
//在迭代期間可以使用entry的value方法的Map的值進行修改
//entry.setValue("bingbing");
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
import java.util.*;
import java.util.Map.*;
/*
* HashMap:去重,因為HashMap的底層與HashSet的底層實現一樣,只是對HashMap去重的時候,操作的是key
* 作業:實現String和Person物件的去重
*/
class Person{
String name;
int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
Person(){}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public boolean equals(Object obj)//傳進來的是Person物件
{
if(!(obj instanceof Person))
throw new ClassCastException("型別不對");
Person p=(Person)obj;
if(this.name==p.name && this.age==p.age)
return true;
else
return false;
}
public int hashCode() {
return name.hashCode()+age*10000;
}
}
public class Demo9 {
public static void main(String[] args) {
//HashMap:無序,去重。它會根據鍵去重,也就是重寫hashCode()和equals方法()
//-----------------------1鍵為String該類的hashCode(),equals()已經重寫過,所以直接用就行了
HashMap<String,Integer> mapStr=new HashMap<String,Integer>();
mapStr.put("hello",1);
mapStr.put("world",2);
mapStr.put("and",3);
mapStr.put("I love",4);
mapStr.put("I love",5);
mapStr.put("my Life",5);
System.out.println(mapStr);
//第一種遍歷方法
Set<String> keys=mapStr.keySet();//得到所有鍵組成的Set
Iterator<String> it=keys.iterator();//用構造器遍歷這個Set
while(it.hasNext())//遍歷鍵的集合
{
String key=it.next();
Integer value=mapStr.get(key);
System.out.println(key+" "+value);
}
System.out.println("-------");
//第二種遍歷方法,用Set存Map中的每一個鍵值對:Map.Entry
Set<Map.Entry<String, Integer>> setStr1=mapStr.entrySet();//把每一個Entry存Set裡
Iterator<Map.Entry<String, Integer>> it2=setStr1.iterator();//遍歷這個Set的,每一項
while(it2.hasNext())
{
Map.Entry<String, Integer> ky=it2.next();//得到一個Set中的值
String key=ky.getKey();
Integer value=ky.getValue();
System.out.println(key+" "+value);
}
//---------------------------1鍵為Person該類的hashCode(),equals()需要重寫
HashMap<Person,String> hashPer=new HashMap<Person,String>();
hashPer.put(new Person("Killy",18),"boy");
hashPer.put(new Person("Jack",19),"trans");
hashPer.put(new Person("Killy",18),"boy");
hashPer.put(new Person("Zoey",20),"boy");
hashPer.put(new Person("Killy",18),"tomBoy");
System.out.println(hashPer);
//第一種遍歷:遍歷鍵
Set<Person> keys3=hashPer.keySet();//鍵的集合
Iterator<Person> it3=keys3.iterator();//迭代鍵
while(it3.hasNext()) {
Person key=it3.next();
String value=hashPer.get(key);
System.out.println(key+" "+value);
}
System.out.println("-----------");
//第二種遍歷:遍歷Map.Entry
Set<Map.Entry<Person, String>> ky2=hashPer.entrySet();//把Map.Entry存到Set集合
Iterator<Map.Entry<Person, String>> it4=ky2.iterator();//得到Set的一每元素,並迭代
while(it4.hasNext()) {
Map.Entry<Person, String> ky=it4.next();//得到每一個Set中存的值
Person key=ky.getKey();
String value=ky.getValue();
System.out.println(key+" "+value);
}
}
}
import java.util.*;
import java.util.Map.*;
/*
* TreeMap:去重和排序,底層與TreeSet一致,在進行排序去重的時候就是去操作key
* 作業:分別使用預設方法和手動方法實現String(key)和People(key)物件的排序去重
*/
class ComWithString implements Comparator<String>//String的構造器,實現手動排序
{
@Override
public int compare(String o1, String o2) {
int num=-(o1.compareTo(o2));//降序
return num;
}
}
class ComWithPeople implements Comparator<People>
{
public int compare(People o1, People o2) {
int num=o1.age-o2.age;
return num==0?o1.name.compareTo(o2.name):num;
}
}
class People implements Comparable<People>//實現該介面進行預設排序,這裡指定泛型People,省很多事
{
String name;
int age;
People(String name,int age){
this.name=name;
this.age=age;
}
People(){}
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(People o) {
int num=this.name.compareTo(o.name);//該方法返回int型正負數,相等時返回0
return num==0?this.age-o.age:num;
}
}
public class Demo10 {
public static void main(String[] args) {
//HsahMap:實現去重排序,是對鍵的處理
//方法一自動排序:實現Comparable介面,重寫CompareTo()方法
//方法二手動排序:實現Comparator介面,重寫Compare()方法
//String方法一自動排序: 實現Comparable介面,重寫CompareTo()方法,這個該類已經實現了(升序),直接用即可
TreeMap<String,Integer> tm1=new TreeMap<String,Integer>();
tm1.put("aaa",1);
tm1.put("aab",2);
tm1.put("aac",3);
tm1.put("abc",4);
tm1.put("bca",5);
tm1.put("aaa",2);
System.out.println(tm1);//輸出{aaa=2, aab=2, aac=3, abc=4, bca=5}
//String方法二手動排序: 實現Comparator介面,重寫Compare()方法,這裡寫成是降序的
//手動排序的優先順序高於自動排序
ComWithString com1=new ComWithString();//建立比較器物件
TreeMap<String,Integer> tm2=new TreeMap<String,Integer>(com1);
//將比較器物件傳給TreeMap的構造方法
tm2.put("aaa",1);
tm2.put("aab",2);
tm2.put("aac",3);
tm2.put("abc",4);
tm2.put("bca",5);
tm2.put("aaa",2);
System.out.println(tm2);//輸出:{bca=5, abc=4, aac=3, aab=2, aaa=2}
//People方法一自動排序: 實現Comparable介面,重寫CompareTo()方法,這裡寫成先按名字排序,再按年齡排序
TreeMap<People,String> treePeo=new TreeMap<People,String>();
treePeo.put(new People("aaaa",18),"boy");
treePeo.put(new People("bbbb",19),"trans");
treePeo.put(new People("bbbb",18),"boy");
treePeo.put(new People("aaaa",18),"boy");
treePeo.put(new People("cccc",18),"tomBoy");
System.out.println(treePeo);
//Peron方法二手動排序: 實現Comparator介面,重寫Compare()方法,這裡寫成是先按年齡排序,再按名字排序
//手動排序的優先順序高於自動排序
ComWithPeople com2=new ComWithPeople();
TreeMap<People,String> treePeo2=new TreeMap<People,String>(com2);
treePeo2.put(new People("aaaa",18),"boy");
treePeo2.put(new People("bbbb",19),"trans");
treePeo2.put(new People("bbbb",18),"boy");
treePeo2.put(new People("aaaa",18),"boy");
treePeo2.put(new People("cccc",20),"tomBoy");
System.out.println(treePeo2);
}
}
import java.util.*;
import java.util.Map.*;
//作業: *練習題二: 1.josgjsjagwajsogiseafgjwsjgvoier
//要求:1.轉化成字串 : a(字元的個數)b()c().. 2.區分大小寫 3.只讀取字母
public class Homework1 {
public static void main(String[] args) {
String s="josgjsjagwajsogiseafgjwsjgvoier";
TreeMap<Character,Integer> words=new TreeMap<Character,Integer>();//基本型別的包裝類實現了方法
for(int i=0;i<=s.length()-1;i++)
{
Character tmp=s.charAt(i);
if((tmp>='a'&&tmp<='z') || (tmp>='A'&&tmp<='A'))//如果是大小寫字母的話
{
if(words.containsKey(tmp))
{
Integer num=words.get(tmp);
words.put(tmp, num+1);
}
else
words.put(tmp,1);
}
}
//遍歷TreeMap
Set<Map.Entry<Character,Integer>> kys=words.entrySet();
Iterator<Map.Entry<Character,Integer>> it =kys.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer> ky=it.next();
Character key=ky.getKey();
Integer value=ky.getValue();
System.out.print(key+"("+value+")");
}
}
}