编程知识 cdmana.com

Javase learning notes 18: Collection (4)

aggregate ( Four )

HashMap and Hashtable The difference between

HashMap Of key It can be for null Do you ?value Well ? Can be empty !

package se3.themap;

import java.util.HashMap;
import java.util.Map;

public class HashMapTest03 {
    public static void main(String[] args) {
        Map map = new HashMap();
        //HashMap The collection allows key by null
        map.put(null,null);
        System.out.println(map.size());//1
        //key Repeated words ,value Will be covered 
        map.put(null,100);
        System.out.println(map.size());//1
        // adopt key obtain value
        System.out.println(map.get(null));//100
    }
}

Hashtable Of key It can be for null Do you ?value Well ? Can't be empty !

package se3.themap;

import java.util.Hashtable;
import java.util.Map;

public class HashTableTest01 {
    public static void main(String[] args) {
        Map map = new Hashtable();
        map.put(null," APO ");
        map.put(1,null);
    }
}
  1. Hashtable and HashMap equally , The bottom layer is the hash table data structure
  2. Hashtable The methods are all with synchronized: Thread safe
  3. Hashtable The initialization capacity of is 11, The default load factor is 0.75
  4. Hashtable Expansion of : Original capacity *2 Again +1

Properties

​ At present, we only need to master Properties The related methods of attribute class objects can be

​ Properties It's a Map aggregate , Inherit Hashtable,Properties Of key and value All are String type

​ Properties It's called an attribute class object

​ Properties It's thread safe

package se3.themap;

import java.util.Properties;

public class PropertiesTest01 {
    public static void main(String[] args) {
        // Create a Properties object 
        Properties pro = new Properties();
        // Need to master Properties Two approaches , A deposit , Take one 
        pro.setProperty("url","jdbc:mysql://localhost:3306/bjpowernode");
        pro.setProperty("driver","com.mysql.jdbc.Driver");
        pro.setProperty("username","root");
        pro.setProperty("password","123");
        // adopt key obtain value
        String url = pro.getProperty("url");
        String driver = pro.getProperty("driver");
        String username = pro.getProperty("username");
        String password = pro.getProperty("password");

        System.out.println(url);//jdbc:mysql://localhost:3306/bjpowernode
        System.out.println(driver);//com.mysql.jdbc.Driver
        System.out.println(username);//root
        System.out.println(password);//123
    }
}

TreeSet

  1. TreeSet The bottom layer of the set is actually a TreeMap
  2. TreeMap At the bottom of the set is a binary tree
  3. Put it in TreeSet The elements in the collection , It's the same as putting TreeMap aggregate key Part of it
  4. TreeSet The elements in the collection : Disorder cannot be repeated , But it can be sorted automatically by the size of the elements , It's called a sortable set .
package se3.set;

import java.util.TreeSet;

public class TreeSetTest02 {
    public static void main(String[] args) {
        // establish TreeSet aggregate 
        TreeSet<String> ts = new TreeSet<>();
        // add to String Elements 
        ts.add(" Qian Qi ");
        ts.add(" Zhang San ");
        ts.add(" Zhao Liu ");
        ts.add(" Li Si ");
        ts.add(" Wang Wu ");
        // Traverse 
        for (String s : ts){
            // In dictionary order , Ascending 
            System.out.print(s + " ");
        }// Zhang San   Li Si   Wang Wu   Zhao Liu   Qian Qi 
        System.out.println();

        TreeSet<Integer> ts2 = new TreeSet<>();
        ts2.add(100);
        ts2.add(200);
        ts2.add(900);
        ts2.add(800);
        ts2.add(600);
        ts2.add(10);
        for (Integer elt : ts2){
            // Ascending 
            System.out.print(elt + " ");
        }//10 100 200 600 800 900
    }
}

About custom type sorting

For custom types ,TreeSet Can I sort it out ? no way

  1. In the following procedure for Person In terms of type , Cannot sort . Because it is not specified Person The rules of comparison between objects
  2. It doesn't say who is big or who is small
  3. The reason for the abnormality is :Person Class does not implement java.lang.Comparable Interface .
package se3.set;

import java.util.TreeSet;

public class TreeSetTest03 {
    public static void main(String[] args) {
        Person p1 = new Person(32);
        Person p2 = new Person(20);
        Person p3 = new Person(30);
        Person p4 = new Person(25);
        // Additive elements 
        TreeSet<Person> persons = new TreeSet<>();
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        // Traverse 
        for (Person p : persons){
            System.out.print(p + " ");
        }
        /** Running results :
         * Exception in thread "main" java.lang.ClassCastException: se3.set.Person cannot be cast to java.lang.Comparable
         *     at java.util.TreeMap.compare(TreeMap.java:1294)
         *     at java.util.TreeMap.put(TreeMap.java:538)
         *     at java.util.TreeSet.add(TreeSet.java:255)
         *     at se3.set.TreeSetTest03.main(TreeSetTest03.java:18)
         */
    }
}
class Person{
    int age;
    public Person(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" + "age=" + age + '}';
    }
}

The custom rules are as follows :

package se3.set;

import java.util.TreeSet;

public class TreeSetTest04 {
    public static void main(String[] args) {
        Person2 p1 = new Person2(32);
        Person2 p2 = new Person2(20);
        Person2 p3 = new Person2(30);
        Person2 p4 = new Person2(25);
        // Additive elements 
        TreeSet<Person2> persons = new TreeSet<>();
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        // Traverse 
        for (Person2 p : persons){
            System.out.println(p);
        }
        /**
         *  Running results :
         * Person{age=20}
         * Person{age=25}
         * Person{age=30}
         * Person{age=32}
         */
    }
}
/*
 Put it in TreeSet Elements in the collection need to implement java.lang.Comparable Interface 
 And realize CompareTo Method ,equals Don't write 
 */
class Person2 implements Comparable<Person2>{
    int age;
    public Person2(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" + "age=" + age + '}';
    }

    // The logic of comparison needs to be written in this method , Or the method of comparison , Compare by what 
    //k.compareTo(t.key)
    // Take the parameters k And every one of the sets k Compare , The return value may be >0 <0 =0
    // Comparison rules are specified by programmers , For example, in ascending or descending order of age 
    @Override
    public int compareTo(Person2 p) {//p1.compareTO(p2)
        //this Namely p1
        //p yes p2
        //p1 and p2 When comparing , Namely this and p Compare 
        /*
        int age1 = this.age;
        int age2 = p.age;
        if(age1 == age2){
            return 0;
        } else if(age1 > age2){
            return 1;
        } else{
            return -1;
        }
        */
        // Abbreviation 
        return this.age - p.age;
    }
}

About the rules of comparison

How to write ? First, in ascending order of age , If they are the same age, they will be in ascending order , Examples are as follows :

package se3.set;

import java.util.TreeSet;

// First, in ascending order of age , If they are the same age, they will be in ascending order 
public class TreeSetTest05 {
    public static void main(String[] args) {
        TreeSet<Vip> vips = new TreeSet<>();
        vips.add(new Vip("a APO ",20));
        vips.add(new Vip("b APO ",20));
        vips.add(new Vip(" Bobo ",18));
        vips.add(new Vip(" wavelet ",17));
        for (Vip vip : vips){
            System.out.println(vip);
        }
        /**
         *  Output results :
         * Vip{name=' wavelet ', age=17}
         * Vip{name=' Bobo ', age=18}
         * Vip{name='a APO ', age=20}
         * Vip{name='b APO ', age=20}
         */
    }
}
class Vip implements Comparable<Vip>{
    String name;
    int age;

    public Vip(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Vip{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    /*
    compareTo The return value of the method is important :
         return 0 It means the same ,value Will be covered 
         return >0, Will continue to look for... On the right subtree 【10-9=1,1>0 The number on the left is larger , So look for... On the right subtree 】
         return <0, Will continue to look for... In the left tree 
     */

    @Override
    public int compareTo(Vip v) {
        if(this.age == v.age){
            // At the same age, sort by name 
            // The name is String type , It can be directly compared to , call compareTo Complete the comparison 
            return this.name.compareTo(v.name);
        } else {
            // Different ages 
            return this.age - v.age;
        }
    }
}

Self balanced binary tree data structure

TreeSet/TreeM It's a self balanced binary tree , Follow the principle of small left and large right ( Compare it when you store it )

Be careful : The process of storage is the process of sorting , Take out is automatically in order of size

100 200 50 60 80 120 140 130 135 180 666 40 55 After storage, it is shown in the figure below

There are three ways to traverse a binary tree

  1. The former sequence traversal : Root left and right
  2. In the sequence traversal : Left root right
  3. After the sequence traversal : Left and right

TreeSet aggregate /TreeMap The set uses : In the sequence traversal

Iterator The iterator uses the middle order traversal ( Left root right )

In the sequence traversal

Using the middle order traversal to extract :

40 50 55 60 80 100 120 140 130 135 180 200 666

Comparator mode implementation TreeSet Sort

package se3.set;

import java.util.Comparator;
import java.util.TreeSet;
/*
TreeSet The second way elements in a collection can be sorted : The way to use a comparator 
 */
public class TreeSetTest06 {
    public static void main(String[] args) {
        // establish TreeSet When we gather , You need to use this comparator 
        //TreeSet<WuGui> wuGuis = new TreeSet<>();// That's not good , Without passing a comparator through the constructor 
        // Pass a comparator to the constructor 
        TreeSet<WuGui> wuGuis = new TreeSet<>(new WuGuiComparator());
        wuGuis.add(new WuGui(1000));
        wuGuis.add(new WuGui(800));
        wuGuis.add(new WuGui(810));
        for (WuGui wuGui : wuGuis){
            System.out.println(wuGui);
        }
        /**
         *  Output results :
         *  Tortoise [age=800]
         *  Tortoise [age=810]
         *  Tortoise [age=1000]
         */
    }
}
// Tortoise 
class WuGui{
    int age;

    public WuGui(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return " Tortoise [" +
                "age=" + age +
                ']';
    }
}
// Write a comparator here alone 
// Comparator implements java.util.Comparator Interface .(Comparable yes java.lang Under bag ,Comparator yes java.util Under bag )
class WuGuiComparator implements Comparator<WuGui>{
    @Override
    public int compare(WuGui o1, WuGui o2) {
        // Specify comparison rules , Sort by age 
        return o1.age - o2.age;
    }
}

Anonymous inner class implementation TreeSet Sort

package se3.set;

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

public class TreeSetTest06 {
    public static void main(String[] args) {
        //TreeSet<WuGui> wuGuis = new TreeSet<>(new WuGuiComparator());
        // Using anonymous inner classes 
        TreeSet<WuGui> wuGuis = new TreeSet<>(new Comparator<WuGui>() {
            @Override
            public int compare(WuGui o1, WuGui o2) {
                return o1.age - o2.age;
            }
        });
        wuGuis.add(new WuGui(1000));
        wuGuis.add(new WuGui(800));
        wuGuis.add(new WuGui(810));
        for (WuGui wuGui : wuGuis){
            System.out.println(wuGui);
        }
        /**
         *  Output results :
         *  Tortoise [age=800]
         *  Tortoise [age=810]
         *  Tortoise [age=1000]
         */
    }
}
// Tortoise 
class WuGui{
    int age;

    public WuGui(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return " Tortoise [" +
                "age=" + age +
                ']';
    }
}

Conclusion

Put it in TreeSet perhaps TreeMap aggregate key Part of the elements want to be sorted , There are two ways :

  1. Put the elements in the collection to implement java.lang.Comparable Interface
  2. In the structure TreeSet perhaps TreeMap Pass it a comparator object when assembling

Comparable and Comparator How to choose ?

When the rules of comparison don't change , Or when the rules of comparison are only 1 When it's time , It is recommended to use Comparable Interface .

If there are more than one comparison rule , And it requires frequent switching between multiple comparison rules , It is recommended to use Comparator Interface .

Collections Tool class

package se3.collection;

import java.util.*;
/*
java.util.Collection  Collection interface 
java.util.Collections  Collection tool class , To facilitate the operation of sets .
 */
public class CollectionsTest01 {
    public static void main(String[] args) {
        //ArrayList Collection is not thread safe 
        List<String> list = new ArrayList<>();
        // Become thread safe 
        Collections.synchronizedList(list);
        list.add("abf");
        list.add("abx");
        list.add("abc");
        list.add("abe");
        // Sort 
        Collections.sort(list);
        for (String s : list){
            System.out.print(s + "  ");
        }//abc  abe  abf  abx
        System.out.println();

        List<WuGui2> wuGui2s = new ArrayList<>();
        wuGui2s.add(new WuGui2(1000));
        wuGui2s.add(new WuGui2(8000));
        // Be careful : Yes List Sort the elements in a collection , Need assurance List The elements in the collection implement Comparable Interface 
        Collections.sort(wuGui2s);
        for (WuGui2 wuGui2 : wuGui2s){
            System.out.println(wuGui2);
        }
        /*
         Tortoise [age=1000]
         Tortoise [age=8000]
        */

        //Set Collection sorting 
        Set<String> set = new HashSet<>();
        set.add("king");
        set.add("kingsoft");
        set.add("king2");
        set.add("king1");
        // take Set Set to List aggregate 
        List<String> mylist = new ArrayList<>(set);
        Collections.sort(mylist);
        for (String s : mylist){
            System.out.print(s + "  ");
        }//king  king1  king2  kingsoft 
    }
}
class WuGui2 implements Comparable<WuGui2>{
    int age;

    public WuGui2(int age) {
        this.age = age;
    }
    @Override
    public int compareTo(WuGui2 o) {
        return this.age - o.age;
    }
    @Override
    public String toString() {
        return " Tortoise [" +
                "age=" + age +
                ']';
    }
}

版权声明
本文为[The most loving girl e]所创,转载请带上原文链接,感谢

Scroll to Top