Java's Map collection, File class, detailed explanation of recursive thinking

Table of contents

1.Map collection:

1. Map collection overview:

2. Comparison between Map collection and collection collection:

3. Implement the use of classes and common methods

2. File class:

1. Overview of the File class:

2. Common methods of the File class:

3. Recursion:

1. Recursive overview:

2. Use of recursion:


1.Map collection:

  1.1 Map collection overview:

  • The Map collection is a double-column collection, a collection of key-value pairs, and each element in the collection contains a key object and a value object.

      Note: the key cannot be repeated, it is unique. The value can be repeated, and the corresponding value can be found through the key

  • Personal understanding: The keys in the Map collection are like subscripts. The subscripts in the List are integers, and the keys in the Map collection can be any type of element. Subscripts are unique, and keys are also unique. The value corresponding to it can be found by key.
  • We often see such a collection: IP address and host name, ID number and individual, system user name and system user object, etc. This one-to-one correspondence relationship is called mapping. Java provides a special collection class to store the objects of this object relationship, that is, java.util.Mapthe interface.

important point:

1. The value in the Map collection can only be found through the corresponding key, and the corresponding value cannot be directly searched.

2. The key is unique and the value can be repeated

1.2 Map collection traversal:

  • There are two ways to traverse the Map collection:

    1. Key value lookup method. Through the key in the element, get the value corresponding to the key

       2. Key-value pair mode. That is, through each key-value pair (Entry) object in the collection, the key and value in the key-value pair (Entry) object are obtained.

     Method 1. Key value lookup method:

   Steps: 1. Use keySet to get all the keys in the Map, and store all the keys in the set collection.

              2. Traverse each key value in the set collection.

              3. Use the get method to get the value corresponding to each key value through the key value.

Code demo:

Set set = hashMap1.keySet();
            for (Object set2 : set) {
                System.out.println(set2);
            }

    Method 2: key-value pair method:

   step:

  1. Use entryset() to obtain all key-value pairs (Entry) objects in the Map collection, and return them in the form of a Set collection.

  2. Traverse the Set collection containing the key-value pair (Entry) object to get each key-value pair (Entry) object.

  3. Call getkey() and getvalue() through the key-value pair (Entry) object to obtain the key and value in the Entry object. 

  What is an Entry key-value pair object:

MapThere are two kinds of objects stored in , one is called key (key), and the other is called value (value). They have a one-to-one correspondence in Map, and this pair of objects is also called Mapone of Entry(项). EntryEncapsulate the corresponding relationship of key-value pairs into objects. That is, a key-value pair object.

The method to get the Entry object:

public Set<Map.Entry<KV>> entrySet() Gets the collection of all key-value pairs in the Map collection (Set collection).

Code demo:

/*
        方式二
         */
       Set<Map.Entry<Object,Object>> set3 = hashMap.entrySet();
       for (Map.Entry<Object,Object> entry:set3) {
           System.out.println("键:"+entry.getKey()+"值"+entry.getValue());
}

2. Comparison between Map collection and collection collection:

  • Both are interfaces under the Java.util package and belong to a level relationship.
  • The Map collection is a double-column collection, and the stored elements appear in pairs. The key of the Map element is unique, and the value can be repeated.
  • The Collection collection is a single-column collection, and the stored elements appear individually. The Set under the Collection interface has unique elements, and the elements in the List collection can be repeated.

The following picture better shows the relationship between the Map collection and the collection collection and their implementation classes:

 

3. Implement the use of classes and common methods

The implementation class implements the abstract method in the Map interface, so there is basically no change in the method. It's just that the implementation of the underlying class is different.

1. Add function:

put(K key,V value) adds the specified value with the specified key in the map to the collection

2. Delete function:
remove(Object key) If it exists, delete the element of the key from the map collection
void clear() Delete all elements from the map collection

3. Length function:

int size() Get the number of elements

4. Get the element:

get(Object key) Get the corresponding value according to the specified key

5. Judgment ability:
boolean containsKey(Object key)
boolean containsValue(Object value)

public class MapTest {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
    
        HashMap hashMap1 = new HashMap();
    
//添加元素
        hashMap.put("数字1:", 1);
        hashMap.put("数字2:", 2);
        hashMap.put("数字2:", 3);
        hashMap.put("数字3:", 99);
        hashMap.put("数字4:", 4);
        hashMap.put("数字5:", null);
Object a=hashMap.get("数字1:");
        //输出的是键值
        System.out.println(a);
        //移除元素
        hashMap.remove("数字5:");
        System.out.println("===========");
        //判断功能
        boolean b = hashMap.containsKey("数字6:");
        System.out.println("集合是否存在这个元素:"+b);
        //获取元素:
        Object o = hashMap.get("数字5:");
        System.out.println("使用get获取到的元素:"+o);
        hashMap.clear();
        System.out.println(hashMap);

 3.1 HashMap implementation class:

 The bottom layer is a hash table data structure. Threads are not synchronized and can store null keys and null values. The uniqueness of the key needs to override the hashCode method and the equals method

important point

1. The access sequence of HashMap is inconsistent. To make the access sequence consistent, LinkedhashMap must be used.

//添加元素
        hashMap.put("数字1:", 1);
        hashMap.put("数字2:", 2);
        hashMap.put("数字2:", 3);
        hashMap.put("数字3:", 99);
        hashMap.put("数字4:", 4);
        hashMap.put("数字5:", null);
     //获取元素
       Object a=hashMap.get("数字1:");
        //输出的是键值
        System.out.println(a);
        //移除元素
        hashMap.remove("数字5:");
        System.out.println("===========");
        //判断功能
        boolean b = hashMap.containsKey("数字6:");
        System.out.println("集合是否存在这个元素:"+b);
        //获取元素:
        Object o = hashMap.get("数字5:");
        System.out.println("使用get获取到的元素:"+o);
Set set = hashMap.keySet();
        for (Object set2 : set) {
            System.out.println(set2);
        }

Output result:

  

2. When using hashmap to store custom type elements, the hashCode method and equals method must be rewritten.

I have already analyzed this in my previous blog : why rewrite the hashCode method, and the equals method

3.2 TreeMap implementation class:

Compared with Map, the TreeMap collection has no unique functions. The underlying data structure is a red-black tree; the keys of elements can be sorted. And his sorting can be divided into natural sorting and comparator sorting.

   Natural sorting : the incoming key value implements the Comparable interface (String, Integer, etc. have already implemented the Comparable interface, so they can be used directly)

//实现了Comeparable接口的自然比较
        TreeMap treeMap1 = new TreeMap();
        treeMap1.put("20",20);
        treeMap1.put("30",30);
        treeMap1.put("410",410);
        treeMap1.put("10",10);
        Set set1 = treeMap1.keySet();
        for(Object set1s:set1){
            System.out.println("键:"+set1s+",值:"+treeMap1.get(set1s));
        }
        System.out.println("------------");

 Comparator sorting: specify the comparator Comparator when creating a TreeMap collection

Note the following when using comparator sorting:

  1. To rewrite the hashCode method, and equals method, to avoid repeated elements.

  2. Implement the Comparator sorter, according to your own sorting rules.

//实现Comparator比较器,进行比较。
        TreeMap<Student,Object> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int result = o1.age - o2.age;
                if (result == 0) {
                    return o1.name.charAt(0) - o2.name.charAt(0);
                }
                return result;
            }
        });
        treeMap.put(new Student("lisi",2000),"beijing");
        treeMap.put(new Student("wangwu",200),"chengdu");
        treeMap.put(new Student("zhangsan",21000),"hsanghai");
        Set set = treeMap.keySet();
        for(Object treemap:set){
            System.out.println(treemap+"值为:"+treeMap.get(treemap));
class Student{
    String name;
    int age;


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

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return age == student.age &&
                name.equals(student.name);

    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", local='" + '\'' +
                '}';
    }

The result of both sorting:

  

2. File class:

1. Overview of the File class:

  • The File class is the only object in the java.io package that represents the disk file itself, that is to say, if you want to operate files and directories in the program, you can do it through the File class

  • The Java.io.File class is an abstract representation of file and directory path names, and is mainly used for operations such as creating, searching, and deleting files and directories.

  • The File class describes files or folders. As long as we want to operate files or folders in Java, we need to find the File class.

important point:

1. The File class can only operate on files and folders on persistent devices. It cannot manipulate the data in the file. Use this IO stream technology when you want to manipulate the data in this file. Therefore, IO streams and File classes generally appear in pairs.

1.2 Construction method:

The File class provides the following three formal construction methods.

  1. public File(String path): If path is an actual path, then the File object represents a directory; if path is a file name, then this File object represents a file.
  2. public File(String parent, String child): Creates a new File instance from the parent pathname string and the child pathname string.

  3. public File(File parent, String child): Creates a new File instance from the parent abstract pathname and child pathname strings.

Use any construction method to create a File object, and then call the methods provided by it to operate on the file. But I think the reason for this is that the second and third methods increase the variety of this file object creation. Our files are inherently diverse, and we can create a different Flie object through this parent path and the subpaths under this path.

The constructor creates a File object based on the path name of the file or folder. Then it is encapsulated into an object of the File class, but the File class does not judge whether the path or file represented by this string exists . Because whether it exists or not does not affect the creation of the File class.

   Note: The File class represents an abstract representation of file and directory pathnames. Then the file or folder represented by the path does not necessarily exist. When we want to operate on the File class object under the path, we need to judge whether the file or folder exists, otherwise, a null pointer exception may be reported when traversing the folder, or an exception may occur in other operations.

Code demo:

//直接创建
        File file = new File("F:\\训练\\javase\\课件\\day16File类");
        //从父类目录以及子目录创建对象
        String parent="F:\\训练\\javase\\课件";
        String child="day16File类\\Excel";
        File file2 = new File(parent, child);

        //通过父级对象和子字符串创建:
        File file3 = new File("F:\\训练\\javase\\课件");
        String childdi="day16File类\\Excel\\123.txt";
        File file4 = new File(file3, childdi);

2. Common methods of the File class:

How to get it:

1. public String getAbsolutePath(): Get the full path (absolute path or real path) of the File object currently calling this method, and return the string of the path.

The difference between an absolute path and a relative path: an absolute path has a drive letter, and a relative path is relative, and generally does not have a drive letter.

 2. public String getPath(): Function: Get the content encapsulated in the object of the current File class, which is similar to method 1.

3. public String getName(): Function: Get the last-level name of the file or directory encapsulated in the object of the File class, that is, get the last-level name in the path depicted by the object.
 

//直接创建
        File file = new File("F:\\训练\\javase\\课件\\day16File类");
//获取该目录的绝对路径
        String path=file.getAbsolutePath();
        System.out.println(path);

        //创建文件目录,已经创建了的文件会报false
        boolean mkdir = file.mkdir();
        System.out.println("创建文件目录:"+mkdir);

        //获取到当前File类的对象中封装的内容
        String path1 = file.getPath();
        System.out.println("封装内容:"+path1);

  

Judgment method:

4. public boolean exists(): Function: If the file or folder in the File class object exists on the hard disk, return true, otherwise return false;

5. public boolean isDirectory(): Function: determine whether it is a folder, if it is a folder, return true, otherwise return false;

6. public boolean isFile(): Function: determine whether it is a file, if it is a file, return true, otherwise return false;

7. public boolean createNewFile(): Function: Create a new empty file if and only if a file with this name does not exist yet.

//创建文件:没有找到对应的文件夹,失败抛出异常。
        boolean newFile = file.createNewFile();

        //判断这个文件是否存在:
        boolean exist1=file.exists();
        System.out.println("文件是否存在:"+exist1);

        //文件夹是否存在:
        boolean isexst1=file.isDirectory();
        System.out.println("文件夹是否存在:"+isexst1);

  

Delete creation method:

8. delete method, if this File represents a directory, the directory must be empty to delete. 2. Function deletion does not go to the recycle bin. Use with caution.

9.public boolean mkdir(): Create the directory represented by this File.

10.public boolean mkdirs(): Create the directory represented by this File, including any required but non-existing parent directories.

//删除文件目录:
        boolean delete = file.delete();
        System.out.println("删除文件目录:"+delete);

        //创建文件:没有找到对应的文件夹,失败抛出异常。
        boolean newFile = file.createNewFile();

//创建文件目录,已经创建了的文件会报false
        boolean mkdir = file.mkdir();
        System.out.println("创建文件目录:"+mkdir);

List method:

11. public String[] list(): returns a String array, representing all sub-files or directories in the File directory.

12. public File[] listFiles(): Returns a File array, representing all sub-files or directories in the File directory.

Note: list returns a String array, which contains String. And listfiles is loaded with an array of files. Inside is the File object.

//h获取当前文件夹的所有目录:必须是实际存在的否则或报错
        File[] files = file.listFiles();
        for (File file1:files) {
            System.out.println("使用listFiles获取所有文件夹:"+file1);
        }

        //获取当前文件夹的目录:返回一个String数组
        int count=0;
        String[] name=file.list();
        for(String names:name){
            count++;
            System.out.println("文件目录含有:"+names);
        }
        System.out.println("该文件夹下有"+count+"个文件夹。");

   

3. Recursion:

1. Recursive overview:

Finish writing tomorrow, it's too late.

2. Use of recursion:

Guess you like

Origin blog.csdn.net/qq_50692350/article/details/126369399
Recommended