The java recursion

What is recursive

  • Recursive : that calls itself a phenomenon in the current method.

Recursive Category:

  • Recursively divided into two types, direct and indirect recursion recursion.
  • Direct method calls itself recursively called themselves.
  • Indirect recursion can be called Method B Method A, B Method C Method calls, C A method of method calls.
Precautions:
  • Recursion limit must be qualified to ensure that recursion can be stopped, otherwise the stack memory overflow may occur. Because: When a method calls another method when the method is called has not been completed, the current method will wait method call is finished.
  • Although there are limited conditions, but not too much recursion recursion. Otherwise stack memory overflow will occur.
  • Constructor disables recursion, reasons: Compile error: constructor is used to create an object, the object has been created can not let go

Recursive must be clear

  • Clear recursive end condition
  • Recursive clear purpose

Recursive cumulative sum

Calculation and 1 ~ n
Analysis: num accumulated = num + (num-1) and and tired, can be accumulated and the operation is defined as a method, recursive calls
Code:
package demo05;

public class GetSum {
    public static void main(String[] args) {

        System.out.println ( "cumulative sum:" + SUM (. 5)); //

    }

    // NUM is 1, the method returns 1, exit the equivalent method, where NUM is always 1 
    public  static  int SUM ( int n-) {
         IF (n-== 1 ) {
             return 1 ;
        }
        // 1, the method returns num + (num-1) num not getSum normalization method calls 
        return n-+ SUM (n-- 1 );
    }
}

note:

Recursion can cause memory frequently create and call the method, it will greatly affect the performance of programs.

Print multi-level directory recursive

Analysis: print multi-level directory, that is, when nested directories. Prior to traverse, I do not know in the end how much level directory, so we still have to use a recursive implementation.
package demo05;

import java.io.File;

public  class GetFile {
     public  static  void main (String [] args) {
         // create File object 
        File dir = new new File ( "C: \\ \\ Administrator IdeaProjects the Users \\ \\ \\ day19 basic_code" );
         // call Print directory method 
        GetFiles (dir);
    }

    public  static  void the GetFiles (File File) {
         // Get sub-directories and files 
        File [] = Files File.listFiles ();
         / *
        Judge:
        When a file, print the absolute path.
        When is a directory, catalog printing method calls continue to form a recursive call.
        * / 
        For (S File: Files) {
             // Analyzing 
            IF (s.isFile ()) {
                 // file, the output file absolute path 
                System.out.println ( "File name:" + s.getAbsolutePath ());
            } The else {
                 // is a folder. Output folder absolute path 
                System.out.println ( "Folder name:" + s.getAbsolutePath ());
                GetFiles(s);
            }
        }
    }
}

File Search

Search finger .java files in the directory.
analysis:
  1. Directory search, directory can not determine how many levels, so the use of recursion, traversing all directories.
  2. While traversing the directory, access to sub-file by file name, to determine eligibility.
package demo05;

import java.io.File;

public class RecurisonFile {
    public static void main(String[] args) {
        //指定目录
        File file = new File("c:\\abc");
        getAllFile(file);
    }

    /*
        Define a method, argument passed directory File type
        Methods for directory traversal
     * / 
    Public  static  void getAllFile (File the dir) {
         // System.out.println (the dir); // print traversed directory name 
        File [] = Files dir.listFiles ();
         for (File F: Files) {
             / / traversal get the file object f judge to determine whether the folder 
            iF (f.isDirectory ()) {
                 // f is a folder, then continue to traverse this folder
                 // we found getAllFile way is to transfer the folder, traversing folder
                 // so the method can be called directly getAllFile: recursive (calls itself) 
                getAllFile (f);
            } The else {
                 // F is a file that can be printed directly 
                / *
                    For example c: \\ abc \\ abc.java
                    As long as the end of the file .java
                    1. File object f, the object into a string

                String name = f.getName();//abc.java
                String path = f.getPath();//c:\\abc\\abc.java
                String s = f.toString();//c:\\abc\\abc.java
                * / 
                // string, lowercase
                 // S = s.toLowerCase ();

                // 2. String class calls the method determines whether the string is .java endsWith end
                 // Boolean B = s.endsWith ( "Java.");

                // 3. If the ending is .java files, then output 
                / * IF (B) {
                    System.out.println(f);
                } * / 
                // chain programmed 
                IF (f.getName (). The toLowerCase (). EndsWith (. "Java" )) {
                    System.out.println(f);
                }
            }
        }
    }
}

File Filter Optimization

To find the specified file, I can use file filters to achieve. ListFiles overloaded and there are two methods, method parameters passed in the filter is the File class. java.io.FileFilter is an interface, a File filter. The objects can be passed to the interface of the File class listFiles (FileFilter) as parameters, only one interface method.

boolean accept (File pathname): test whether pathname should be included in the current File directory, in line with returns true.
analysis:
  • Interface as parameters, need to pass subclass object, wherein the method override. The method of determining retention rules. We chose an anonymous inner class way, it is relatively simple.
  • accept methods, parameters for the File, means that all sub-files and subdirectories under the current File. Retain Returns true, filter out false.

Retention rules:

  • Either meet the requirements document.
  • Either directory to continue traversing.
  • By the action of the filter, the array elements returned listFiles (FileFilter), the sub-file objects are qualified, can be printed directly.

Using filters must clear two things

accept method filter who called?

  • accept method listFiles filter method will call parameters in the

What parameters pathname accept method is?

  • Each File object will traverse the method listFiles obtained, pathname accept the arguments passed to the method
package demo06;


import java.io.File;
import java.io.FileFilter;

public  class Demo01File {
     public  static  void main (String [] args) {
         // create File object 
        File dir = new new File ( "C: \\ \\ Administrator IdeaProjects the Users \\ \\ \\ day19 basic_code" );
         // call Print directory method 
        GetFiles (dir);
    }

    public  static  void the GetFiles (File File) {
         // Get sub-directories and files 
        File [] = File.listFiles Files ( new new the FileFilter () {
            @Override
            // anonymous inner classes manner, create a filter subclass object 
            public  Boolean Accept (File pathname) {
                 return pathname.getName () endsWith ( "Java.") ||. Pathname.isDirectory ();
            }
        });
        /*
        Judge:
        When a file, print the absolute path.
        When is a directory, catalog printing method calls continue to form a recursive call.
        * / 
        For (S File: Files) {
             // Analyzing 
            IF (s.isFile ()) {
                 // file, the output file absolute path 
                System.out.println ( "File name:" + s.getAbsolutePath ());
            } else {
                GetFiles(s);
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/wurengen/p/12071152.html