Recursion

Recursion

  1. 所谓递归(Recursion),就是方法调用自身。对于递归来说,一定有一个出口,让递归借宿,只有这样才能保证不出现死循环。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Test {
public int compute(int numnber) {
if (numnber == 1) {
return 1;
} else {
return numnber * compute(numnber - 1);
}
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.compute(5));
}
}
public class FileTest {
public static void deleteAll(File file) {
if (file.isFile() || file.list().length == 0) {
file.delete();
} else {
File[] files = file.listFiles();
for (File file1 : files) {
deleteAll(file1);
file.delete();
}
}
}
public static void main(String[] args) {
File file = new File("/Users/bob/Downloads/activiti-5.16.41");
deleteAll(file);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 循环遍历文件夹
*/
public class ListAllTest {
//用于判断目录或文件所处的层次
private static int time;
public static void deepList(File file) {
if (file.isFile() || file.listFiles().length == 0) {
return;
} else {
File[] files = file.listFiles();
files = sort(files);
for (File file1 : files) {
StringBuffer stringBuffer = new StringBuffer();
if (file1.isFile()) {
stringBuffer.append(getTabs(time));
stringBuffer.append(file1.getName());
} else {
stringBuffer.append(getTabs(time));
stringBuffer.append(file1.getName());
stringBuffer.append("\\");
}
System.out.println(stringBuffer.toString());
if (file1.isDirectory()) {
time++;
deepList(file1);
time--;
}
}
}
}
//整理文件数组,使得目录排在文件之前
private static File[] sort(File [] files){
List<File> list = new ArrayList<>();
for (File file : files) {
if (file.isDirectory()) {
list.add(file);
}
}
for (File file : files) {
if (file.isFile()) {
list.add(file);
}
}
return list.toArray(new File[files.length]);
}
//判断需要加多少个tab
private static String getTabs(int time) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < time; i++) {
stringBuffer.append("\t");
}
return stringBuffer.toString();
}
public static void main(String[] args) {
File file = new File("/Users/bob/Downloads/activiti-5.16.4");
deepList(file);
}
}