日誌集合類知識學習

一、集合概述
  1. java中集合有3大類:List、Set、Map
    • List接口:有序的集合,能通過索引訪問列表中的元素,類似數組。
      • 實現List接口的常用類:LinkedList,ArrayList,Vector和Stack
    • Set接口:不包含重複元素的集合,即set中的任何e1.equals(e2)=false。set中最多有一個null。
    • key-value映射的鍵值對。
      • 實現Map的常用類:HashTable、HashMap
二、實例:
      Map接口 
  1. Map接口常用方法   
  • put(key,value);//向map中加入元素
  • contiansKey(Object key);//key在map中是否存在
  • contiansValue(Object value);//value在map中是否存在

  • keySet()  返回此映射中所包含的鍵的 Set 視圖。
  • get(Object key) 返回指定鍵所映射的值,若對於該鍵值來說此映射不包含任何映射,則返回NULL
     2. 實例
<span style="font-size:14px;">import java.util.*;
public class HashMapDemo
{
 public static void main(String[] args){
  //註冊用戶
  HashMap users = new HashMap();
  users.put("luqh1",new User("luqh1","1")); //
  users.put("luqh2",new User("luqh2","2"));
  users.put("luqh3",new User("luqh3","3"));
  users.put("luqh3","zyf");
        Set keySet = users.keySet();
        System.out.println(keySet);
        User user1 = new User("luqh1","1");
  System.out.println("users.containsValue("+"zyf"+"):"+users.containsValue("zyf"));
  //登錄查找
        Scanner s = new Scanner(System.in);
  while(true){
   System.out.print("姓名:");
   String name = s.nextLine();
   System.out.print("密碼:");
   String pwd = s.nextLine();
   if(!users.containsKey(name)){
      System.out.println("用戶不存在");
      continue;
   }
   User user = (User)users.get(name);//通過name獲取到value
   if(user.pwd.equals(pwd)){
    System.out.println(name+"登錄成功");
    continue;
   }
  }
 }
}
class User
{
 String name;
 String pwd;
 public User(String name,String pwd){
  this.name=name;
  this.pwd = pwd;
 }
 public String toString(){
  return name+":"+pwd;
 }
}</span>
輸出結果:

[luqh1, luqh3, luqh2]
users.containsValue(zyf):true
姓名:luqh1
密碼:1
luqh1登錄成功
       3. HashMap和HashTable的區別
  •   HashMap                                                    HashTable
                      非線程安全                                                   線程安全
                      快                                                                 稍微慢點
  •  舉例子說明HashMap的非線程安全(網上實例)
<span style="font-size:14px;">public class HashMapThread {
	public static final HashMap<String,String> firstHashMap = new HashMap<String, String>();


	public static void main(String[] args) throws Exception {
		//線程1
		Thread t1 = new Thread(){
			public void run(){
				for(int i=0;i<25;i++){
					firstHashMap.put(String.valueOf(i), String.valueOf(i));	
				}
				
			}
		};
		Thread t2 = new Thread(){
			public void run(){
				for(int j=25;j<50;j++){
					firstHashMap.put(String.valueOf(j), String.valueOf(j));
				}
			}
		};
		t1.start();
		t2.start();
		Thread.currentThread().sleep(1000);//注線程休息1秒,以便於t1,t2鏈各個線程填充firstHashMap完成
		//如果key和value不同,說明兩個線程在同步的時候HashMap出現了異常
		for(int l = 0;l<50;l++){
			if(!String.valueOf(l).equals(firstHashMap.get(String.valueOf(l)))){
				System.out.println(String.valueOf(l)+":"+firstHashMap.get(String.valueOf(l)));
			}
		}
	}
}</span>
            自己驗證之後的結果是:
            2:null
            5:null
            7:null
            9:null
       Set接口:無序不重複
  1. 實現類有hashSet
  2. 常用方法:
  3. 實例
<span style="font-size:14px;">package MAP;

import java.util.HashSet;
import java.util.Set;

public class HashSetDemo {
public static void main(String[] args) {
 Set<Node> foods = new HashSet<Node>();
 foods.add(new Node(3,4));
 foods.add(new Node(5,6));
 foods.add(new Node(6,7));
 foods.add(new Node(8,9));
 System.out.println(foods.size());
 System.out.println(foods);//必須有toStrig方法,才成輸出自己想要的[3,4]結果
 
 //吃一顆豆子
 foods.remove(new Node(8,9));
 System.out.println(foods);//必須有toStrig方法,才成輸出自己想要的[3,4]結果
 for(int i=0;i<10;i++){
  for(int j=0;j<10;j++){
   if(foods.contains(new Node(i,j))){
    System.out.println("0");
   }else
    System.out.println("");
  }
 }
  }
}

class Node{
 private int i;
 private int j;
 public Node(int i,int j){
      this.i=i;
      this.j=j;
 }
//必須寫equals方法
/*原因:
集合中的contains其實也是用equals來比較的;
默認equals在比較兩個對象時,是看他們是否指向同一個地址的,
但有時,我們希望兩個對象只要是某些屬性相同就認爲他們的quals爲true。比如:
Node n1 = new Node(3,4);
Node n2 = new Node(3,4);
如果不重寫equals的話,他們是不相同的,所以我們要重寫equals,判斷只要他們的id和名字相同equals就爲true
這也正是foods.contains(new Node(3,4)爲true的原因。
*/
public boolean equals(Object obj){
 if(obj==null){
  return false;
 }
 if(this==obj){
  return true;
 }
 if(obj instanceof Node){
  Node o = (Node)obj;
  return i==o.i && j ==o.j;
 }
 return false;
}
//上面講述了爲什麼要重新equals,一般重寫了equals,也也重寫hashCode()
//hashCode的常規規定:兩個相同的對象,hashCode也一樣;
//當 對象.eauals(新對象)=true時,hashCode重寫之後也會一樣;
public int hashCode(){
 return (i<<16)|j;
}
//必須有toStrig方法,System.out.println(foods);才成輸出自己想要的[3,4]結果
public String toString(){
 return "["+i+","+j+"]";
}
}</span>
  List接口
  1. 常用子類:ArrayList 、Vector,常用的是ArrayList
  2. 實例:常用API方法舉例:
  3. list的增加、刪除常用方法
<span style="font-size:14px;">public class ArrayListDemo {
public static void main(String[] args) {
 //List<String> list = new ArrayList<String>();
 //指定操作的泛型爲String類型
 List<String> list = null;
 list = new ArrayList<String>();
 list.add("how are you!");
 list.add(0, "luqh");
 list.add(1,"hello");
 System.out.println("刪除之前"+list);
 //根據索引刪除
 list.remove(0);
 //根據內容刪除
 list.remove("hello");
 System.out.println("刪除之後"+list);
}
}
//輸出結果:刪除之前[luqh, hello, how are you!]
                    刪除之後[how are you!]</span>
   4. List的輸出
<span style="font-size:14px;">public static void main(String[] args) {
 List<String> list = new ArrayList<String>();
 list.add("how old are you!");
 list.add(0, "luqh");
 list.add(1,"hello");
 //正序輸出
 for(int i = 0;i<list.size();i++){
  System.out.print(list.get(i)+"、");
 }
 System.out.println("");
 //逆序輸出
 for(int k=list.size()-1;k >= 0;k--){
  System.out.print(list.get(k)+"、");
 }
 System.out.println("");
 //按適當順序(從第一個到最後一個元素)返回包含此列表中所有元素的數組;返回數組的運行時類型是指定數組的運行時類型
 String[] str = list.toArray(new String[]{});
 for(int j= 0;j<str.length;j++){
  System.out.print(str[j]+"、");
 }
}</span>
輸出結果
luqh、hello、how old are you!、
how old are you!、hello、luqh、
luqh、hello、how old are you!、

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