Java learning notes - basic syntax Ⅷ - generics, Map

generic paradigm

Generic type is essentially a parameterized type, that is, the operated data type is specified as a parameter, that is, the type is parameterized from the original specific type, and then the specific type is passed in during use / call. This parameter type can be used in classes, methods and interfaces, including generic classes, generic methods and generic interfaces

// Generic class
public class GenericDemo <T>{
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
// Test class
public class Demo {
    public static void main(String[] args) {
        GenericDemo<String> gd1 = new GenericDemo<>();
        gd1.setT("Lin Qingxia");
        System.out.println(gd1.getT());
        System.out.println("--------");
        GenericDemo<Integer> gd2 = new GenericDemo<>();
        gd2.setT(18);
        System.out.println(gd2.getT());
    }
}

Here, it is best to specify the data type when creating generic class objects in the test class

Generic method:

public class GenericFunc {
    public <T>void show(T t){
        System.out.println(t);
    }
}
public class Test {
    public static void main(String[] args) {
        GenericFunc gf = new GenericFunc();
        gf.show("Hello");
    }
}

Generic interface:

public interface Generic <T>{
    void show(T t);
}
public class GenericImpl<T> implements Generic<T>{
    @Override
    public void show(T t) {
        System.out.println(t);
    }
}
public class Demo {
    public static void main(String[] args) {
        Generic<String> gc1 = new GenericImpl<>();
        gc1.show("Hello");

        Generic<Integer> gc2 = new GenericImpl<>();
        gc2.show(100);
    }
}

Type wildcard

To represent the parent classes of various generic lists, you can use type wildcards

  • Type wildcard: <? >
  • List<?> Represents a list whose element type is unknown, and its elements can match any type
  • This List with wildcards only indicates that it is the parent of various generic lists, and cannot add elements to it
import java.util.ArrayList;
import java.util.List;

public class MyGeneric {
    public static void main(String[] args) {
        List<?> list1 = new ArrayList<String>();
        // Cannot add
//        list1.add(12);
        List<String> list2 = new ArrayList<>();
        // Cannot add
        list2.add("Hello");
        System.out.println(list2);
    }
}
public static <T> void test(List<T> c, T t){
    // Can add
    c.add(t);
}

So what is the use of type wildcards

import java.util.List;

public class MyGeneric {
    public  void test3(List<?> c){
        for (int i = 0; i < c.size(); i++) {
            System.out.println(c.get(i));
        }
    }
}
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        MyGeneric mg = new MyGeneric();
        List<String> ls1 = new ArrayList<>();
        ls1.add("Hello");
        ls1.add("World");
        mg.test3(ls1);
        System.out.println("-------");
        List<Integer> ls2 = new ArrayList<>();
        ls2.add(66);
        ls2.add(666);
        mg.test3(ls2);
    }
}

If you don't know the type parameters, you can use type wildcards, and you can also use the upper limit and lower limit of type wildcards

Variable parameters:

  • * in python and
  • Variable parameters are arrays like python
  • If a method has multiple parameters, including variable parameters, the variable parameters should be placed last

Map collection

Map collection overview:

  • Interface map < K, V > k is the type of key and V is the type of value
  • Objects that map keys to values cannot contain duplicate keys, and each key can be mapped to at most one value

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

public class MapDemo {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        System.out.println(map.put("abc","123"));
        // null
        System.out.println(map);
    }
}

Acquisition of Map:

  • Get the: get method according to the key and return V
  • Get all keys: the keySet method returns the Set set, because the keys are not repeated
  • Get all values: the values method returns Collection, and the values are repeatable
  • Get key value pair: entrySet method
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("1","machine learning");
        map.put("2","Deep semester");
        map.put("3","natural language processing");
        map.put("4","computer vision ");
        // Get the value through the specific key
        String s = map.get("1");
        System.out.println(s);
        // Get all keys and return Set
        Set<String> strings = map.keySet();
        System.out.println(strings);
        // Get all the values and return the Collection
        Collection<String> values = map.values();
        System.out.println(values);
        // Through entrySet method
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for(Map.Entry<String, String> me:entries){
            System.out.println(me.getKey()+" "+me.getValue());
        }
    }
}
machine learning
[1, 2, 3, 4]
[machine learning, Deep semester, natural language processing, computer vision ]
1 machine learning
2 Deep semester
3 natural language processing
4 computer vision 

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

public class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] strings = line.split("");
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i<strings.length;i++){
            String string = strings[i];
            if(map.containsKey(string)){
                Integer integer = map.get(string);
                integer += 1;
                map.put(string,integer);
            }else{
                map.put(string,1);
            }
        }
        // ergodic
        Set<String> strings1 = map.keySet();
        for(String s:strings1){
            Integer integer = map.get(s);
            System.out.print(s+"("+integer+")");
        }
    }
}

I learned the tool class Arrays of a collection before. Now I learn another tool class Collections

With this tool class, even ArrayList can be sorted (TreeSet was learned earlier)

// Student class
public class Student {
    private int age;
    private String name;

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
// Test class
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Demo {
    public static void main(String[] args) {
        Student s1 = new Student(18,"Zhang San");
        Student s2 = new Student(19,"Li Si");
        Student s3 = new Student(18,"Wang Wu");
        ArrayList<Student> arr = new ArrayList<>();
        arr.add(s1);
        arr.add(s2);
        arr.add(s3);
        Collections.sort(arr, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num1 = o1.getAge()-o2.getAge();
                int num2 = num1 == 0?o1.getName().compareTo(o2.getName()):num1;
                return num2;
            }
        });
        for(Student s:arr){
            System.out.println(s.getAge()+" "+s.getName());
        }
    }
}

// Implementation 1
import java.util.ArrayList;
import java.util.Collections;

public class PokerDemo {
    public static void main(String[] args) {
        ArrayList<String> arr = new ArrayList<>();
        String [] color = {"♦","♥","♣","♠"};
        String [] point = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
        for(int i = 0;i< color.length;i++){
            for(int j = 0;j< point.length;j++){
                String s = color[i] + point[j];
                arr.add(s);
            }
        }
        Collections.shuffle(arr);
        ArrayList<String> p1 = new ArrayList<>();
        ArrayList<String> p2 = new ArrayList<>();
        ArrayList<String> p3 = new ArrayList<>();
        ArrayList<String> p4 = new ArrayList<>();
        for(int i = 0;i<arr.size();i++){
            if(i> arr.size()-3){
                p4.add(arr.get(i));
            }else if(i%3==0){
                p1.add(arr.get(i));
            }else if(i%3==1){
                p2.add(arr.get(i));
            }else if(i%3==2){
                p3.add(arr.get(i));
            }
        }
        System.out.println(p1);
    }
}
// Implementation 2
import java.util.*;

public class Poker {
    public static void main(String[] args) {
        // Using HashMap to store a deck of playing cards
        HashMap<Integer,String> poker = new HashMap<>();
        String [] color = {"♦","♥","♣","♠"};
        String [] point = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
        int index = 0;
        ArrayList<Integer> arrIndex = new ArrayList<>();
        for(int i = 0;i<color.length;i++){
            for(int j =0;j< point.length;j++){
                String s = color[i] + point[j];
                poker.put(index,s);
                arrIndex.add(index);
                index++;
            }
        }
        poker.put(index,"Xiao Wang");
        arrIndex.add(index);
        index++;
        poker.put(index,"king");
        arrIndex.add(index);
        // Storing the index with ArrayList will disrupt the index

        // Scramble sort
        Collections.shuffle(arrIndex);
//        System.out.println(arrIndex);
        // In order to get the cards in order, use the TreeSet set
        TreeSet<Integer> player1 = new TreeSet<>();
        TreeSet<Integer> player2 = new TreeSet<>();
        TreeSet<Integer> player3 = new TreeSet<>();
        TreeSet<Integer> referee = new TreeSet<>();
        // Deal cards to players
        for(int i = 0;i<arrIndex.size();i++){
            Integer num = arrIndex.get(i);
            if(i>=arrIndex.size()-3){
                referee.add(num);
            }else if(i%3 == 0){
                player1.add(num);
            }else if(i%3 == 1){
                player2.add(num);
            }else if(i%3 == 2){
                player3.add(num);
            }
        }
        // Look at cards and package them into functions
        showPoker("Player1",player1,poker);
        showPoker("Player2",player2,poker);
        showPoker("Player3",player3,poker);
        showPoker("Referee",referee,poker);
    }
    // Incoming players, playing cards, maps
    public static void showPoker(String name,TreeSet<Integer>ts,HashMap<Integer,String>map){
        System.out.println(name+"The cards are:");
        System.out.print("\t");
        for(Integer i:ts){
            String s = map.get(i);
            System.out.print(s+", ");
        }
        System.out.println();
    }
}

Keywords: Java JavaSE

Added by Atomic Taco on Sun, 26 Dec 2021 15:05:45 +0200