Java Reference
In-Depth Information
✓
✓
20.13
Show the call stack for
isPalindrome("abcba")
using the method defined in
Listing 20.4.
Check
Point
20.14
Show the call stack for
selectionSort(new double[]{2, 3, 5, 1})
using the
method defined in Listing 20.5.
20.15
What is a recursive helper method?
Recursive methods are efficient for solving problems with recursive structures.
Key
Point
The preceding examples can easily be solved without using recursion. This section presents a
problem that is difficult to solve without using recursion. The problem is to find the size of a
directory. The size of a directory is the sum of the sizes of all files in the directory. A directory
d
may contain subdirectories. Suppose a directory contains files
f
1
,
f
2
, . . . ,
f
m
and subdirecto-
VideoNote
ries
d
1
,
d
2
, . . . ,
d
n
,
as shown in Figure 20.5.
Directory size
directory
f
1
f
2
f
m
. . .
d
1
d
2
d
n
. . .
F
IGURE
20.5
A directory contains files and subdirectories.
The size of the directory can be defined recursively as follows:
size
(
d
)
=
size
(
f
1
)
+
size
(
f
2
)
+
. . .
+
size
(
f
m
)
+
size
(
d
1
)
+
size
(
d
2
)
+
. . .
+
size
(
d
n
)
The
File
class, introduced in Section 14.10, can be used to represent a file or a directory and
obtain the properties for files and directories. Two methods in the
File
class are useful for
this problem:
The
length()
method returns the size of a file.
■
The
listFiles()
method returns an array of
File
objects under a directory.
■
Listing 20.7 gives a program that prompts the user to enter a directory or a file and dis-
plays its size.
L
ISTING
20.7
DirectorySize.java
1
import
java.io.File;
2
import
java.util.Scanner;
3
4
public class
DirectorySize {
5
public static void
main(String[] args) {
6
// Prompt the user to enter a directory or a file
7 System.out.print(
"Enter a directory or a file: "
);
8 Scanner input =
new
Scanner(System.in);
9 String directory = input.nextLine();
10
11
// Display the size
12 System.out.println(
getSize(
new
File(directory))
+
" bytes"
);
invoke method
13 }
14