Notes - Java foundation advanced 2

Set set

import java.util.*;
public class HashSetDemo{
    public static void main(String[] args){
    //Features of Set interface
    //Is a collection without index, duplicate elements are not allowed to be stored
    //HashSet inherits from Set interface
    Set<String> aSet = new HashSet<String>();
    //The Set interface also inherits from the Collection interface, so it also inherits its methods
    aSet.add("Li Bai");
    aSet.add("Du Fu");
    aSet.add("Su Shi");
    aSet.add("Xin Qiji");
    aSet.add("Xin Qiji");
    System.out.println(aSet);//[Xin Qiji, Li Bai, Du Fu, Su Shi], the output result is out of order, which can not be repeated. This is the characteristic of HashSet set set
    //Without index, index cannot be traversed with for loop
    //For traversal, iterator can be used to call Collection method iterator, and an iterator will be returned
    Iterator<String> iterator = aSet.iterator();
    //Using Iterator's method hasNext, and next to traverse the collection
    while(iterator.hasNext()){
        String str = iterator.next();
        System.out.println(str);
    }
    System.out.println("=========================");
    //Enhance for loop traversal
    for(String str1 :aSet){
        
        System.out.println(str1);
    }
    }
}

Hash value

public class Person{
    
}
//Hash value: it is a decimal integer, given randomly by the system
//Is an object address value, is a logical address, is obtained by simulation
//Is not the physical address where the data is actually stored
//There is a method in the Object class that can get the hash value of the Object
public class HashCodeDemo{
    public static void main(String[] args){
    Person p1 = new Person();
    //Calling the HashCode method will return a hash value
    int hashCode = p1.hashCode();
    System.out.println(hashCode);//991505714
    
    }
}

The principle of non repetition of Set set storage elements

When the Set collection calls the add method, the add method will call the element's hashCode method and equals method to determine whether the element is duplicate. If the hashCode and equals are the same, they will not be added to the collection. To ensure that the hashCode and equals are different, the hashCode and equals methods must be rewritten

LinkedHashSet

import java.util.*;
public class LinkedHashSetDemo{
    public static void main(String[] args){
    LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add("Li Bai");
    linkedHashSet.add("Su Shi");
    linkedHashSet.add("Li Qingzhao");
    linkedHashSet.add("Du Fu");
    linkedHashSet.add("Li Bai");
    System.out.println(linkedHashSet);//[Li Bai, Su Shi, Li Qingzhao, Du Fu], orderly and unrepeatable

    
    } 
}

Variable parameters

//According to the principle of variable parameters, the bottom layer of variable parameters is an array. Depending on the number of parameters passed / /, arrays of different lengths will be created
public class VarArgsDemo{
    public static void main(String[] args){
    int num = method(1,2,3,4,5);
    System.out.println(num);
    }
    public static int method(int...arr){
    
    int sum = 0;
    for(int i=0;i<arr.length;i++){
        sum = sum+arr[i];
    }
    return sum;
    }
}

Collections collection utility class operates on collections

import java.util.*;
public class CollectionsDemo{
    public static void main(String[] args){
    ArrayList<Integer> arraylist = new ArrayList<>();
    //addAll adds elements to the collection, static methods, and calls directly
    Collections.addAll(arraylist,1,2,3,4,5);
    System.out.println(arraylist);
    }
}
public class Person implements Comparable<Person>{
    private String name;
    private int age;
    
    public Person(){}
    
    public Person(String name,int age){
        this.name=name;
        this.age=age;
    }
    //Overriding toString will call toString's method when outputting the object
    public String toString(){
        String str = "name="+name+" age="+age;
        return str;
    }
    
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return age;
    }
    //Override compareTo method
    public int compareTo(Person o){
        //Collation of compatible interface, self parameter, ascending
        return this.getAge()-o.getAge();
    }
}
import java.util.*;
//Sort sets
public class SortDemo{
    public static void main(String[] args){
    ArrayList<Integer> list = new ArrayList<>();
    list.add(4);
    list.add(2);
    list.add(3);
    list.add(1);
    //Use the sort method of Collections to sort
    Collections.sort(list);
    System.out.println(list);
    //How to sort objects
    //To sort objects, you need to implement an interface Comparable
    //And override the method compareTo in the interface to define the sorting rules
    Person p1 = new Person("Li Bai",22);
    Person p2 = new Person("Du Fu",23);
    Person p3 = new Person("Li Qingzhao",18);
    ArrayList<Person> list1 = new ArrayList<>();
    list1.add(p1);
    list1.add(p2);
    list1.add(p3);
    System.out.println(list1);
     //Sort people by age
    Collections.sort(list1);
    System.out.println(list1);//[name = Li Qingzhao age=18, name = Li Bai age=22, name = Du Fu age=23]
    }
}

Map set

Map set points:

  1. When Map set is a two column set, Map < K, V >

  2. The data types of the elements, key and value in the Map set can be the same or different

  3. The elements in the Map 'collection are not allowed to be duplicate when key is used, and can be duplicate when value is used

  4. The elements in the Map set, key and value are one-to-one corresponding

Implementation classes of common Map sets

HashMap collection:

The HashMap collection implements the Map interface

  1. The hash table at the bottom of the HashMap collection is very fast in query
  2. The HashMap collection is an unordered collection

LinkedHashMap collection

The LinkedHashMap collection inherits the HashMap collection

  1. Fast query speed

  2. Ordered set

Common methods in Map interface

import java.util.*;
//Common methods of Map collection
public class MapDemo{
    public static void main(String[] args){
    //Using the implementation class HashMap of Map collection to create polymorphism
    Map<String,String> aMap = new HashMap<>();
    //Method put to add key value pairs to a collection
    aMap.put("Zhou Yu","Little Joe");
    aMap.put("Sun CE","Big Joe");
    aMap.put("Lv Bu","army officer's hat ornaments");
    System.out.println(aMap);//Lu Bu = Diao Chan, sun CE = Da Qiao, Zhou Yu = Xiao Qiao}
    //Duplicate keys are not allowed to be stored in the Map set. If they are repeated, the value of the later key will be replaced by the original value
    aMap.put("Lv Bu","Xi Shi");
    System.out.println(aMap);//Lu Bu = Xi Shi, sun CE = Da Qiao, Zhou Yu = Xiao Qiao}
    
    System.out.println("=========Manual split line==========");
    //get method, according to the specified key, gets the corresponding value
    String str = aMap.get("Zhou Yu");
    System.out.println(str);//Little Joe
    //containsKey(); judge whether the set contains the specified key, and return boolean
    boolean b = aMap.containsKey("Lv Bu");
    System.out.println(b);//true
    //remove: delete the key value corresponding to the specified key and return the value of the deleted element
    String str2 = aMap.remove("Lv Bu");
    System.out.println(str2);//Xi Shi
    System.out.println(aMap);//{sun CE = Daqiao, Zhou Yu = Xiaoqiao}   
    
    }
}

Map traversal build value

import java.util.*;
public class KeySetDemo{
    public static void main(String[] args){
    Map<String,Integer> aMap = new HashMap<>();
    aMap.put("Big Joe",22);
    aMap.put("Little Joe",20);
    aMap.put("Wang Zhaojun",24);
    aMap.put("Yang Yuhuan",26);
    //The first way to traverse a Set is to obtain a Set containing all keys through the keySet method in the Map Set
    Set<String> aSet =aMap.keySet();
    //Get iterator
    Iterator<String> iterator = aSet.iterator();
    //First determine whether there is a next element, and then get the Key
    while(iterator.hasNext()){
    String aKey = iterator.next();
    Integer aInteger = aMap.get(aKey);
    System.out.println(aKey+"-"+aInteger);
    }
    System.out.println("Manual split line");
    //Enhance for Chapter 2 traversal
    for(String bKey:aSet){
        Integer bInteger = aMap.get(bKey);
        System.out.println(bKey+"-"+bInteger);
    }
    
    //The third way is to use Entry object traversal
    //Implementation steps
    /*
    1.Use the method entrySet () in the Map collection to take out multiple entry (key value pair) objects in the collection and save them in a Set collection
    2.Traverse the Set set to get each object
    3.Use the methods getKey() and getValue() in the Entry object to get the key and value
    */
    System.out.println("=============");
    Set<Map.Entry<String,Integer>> set = aMap.entrySet();
    //Enhanced for
    for(Map.Entry<String,Integer> entry : set){
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key+"-"+value);
    }
    
    }
}
package demo14;

import java.util.Objects;

public class Person {
    private String name;
    private  int age;

    public Person() {
    }

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

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package demo14;

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

public class PersonDemo {
    public static void main(String[] args) {
        show1();
    }
    private static void show1(){
        //To ensure that the stored key s are unique, the hashCode and equals methods must be overridden
        HashMap<Person,String > map = new HashMap<>();
        map.put(new Person("Queen",18),"Britain");
        map.put(new Person("Qin Shi Wang",19),"the Qin state");
        map.put(new Person("Vladimir Putin",18),"Russia");
        map.put(new Person("Queen",18),"U.S.A");
        Set<Map.Entry<Person,String >> set = map.entrySet();
        for(Map.Entry<Person,String > entry:set){
            Person key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"--"+value);
        }
    }

    private static void show() {
        HashMap<String,Person> map = new HashMap<>();
        map.put("Beijing",new Person("Zhang San",18));
        map.put("Shanghai",new Person("Li Si",19));
        map.put("Guangzhou",new Person("Wang Wu",20));
        map.put("Beijing",new Person("Zhao Liu",18));
        Set<String> set = map.keySet();
        for(String key :set){
            Person value = map.get(key);
            System.out.println(key+"--"+value);
        }
    }

}

LinkedHashMap collection

package demo14;

import java.util.HashMap;
import java.util.LinkedHashMap;

//LinkedHashMap inherited from HashMap
public class LinkedHashMapDemo {
    public static void main(String[] args) {
    //It's an ordered set
    HashMap<String,String> map  = new LinkedHashMap<>();
    map.put("a","a");
    map.put("c","c");
    map.put("d","d");
    map.put("a","b");
    System.out.println(map);//{a=b, c=c, d=d}, ordered, not repeated
}
}

Hashtable set

The Hashtable collection inherits from the Map interface

Hashtable cannot store null value of null key. Now this collection has been eliminated, but its subclass Properties collection is still active. It is a collection combined with IO flow

Tags: Java Amap

Posted on Wed, 06 Nov 2019 12:52:59 -0500 by zurron