p.97 foreach syntax
Many for statements involve stepping through a sequence of integral values, like this:
for(int i = 0; i < 100; i++)For these, the foreach syntax won’t work unless you want to create an array of int first. To
simplify this task, I’ve created a method called range( ) in net.mindview.util.Range that
automatically generates the appropriate array. My intent is for range( ) to be used as a
static import:
//: control/ForEachInt.java
import static net.mindview.util.Range.*;
import static net.mindview.util.Print.*;
public class ForEachInt {
public static void main(String[] args) {
for(int i : range(10)) // 0..9
printnb(i + " ");
print();
for(int i : range(5, 10)) // 5..9
printnb(i + " ");
print();
for(int i : range(5, 20, 3)) // 5..20 step 3
printnb(i + " ");
print();
}
} /* Output:
0 1 2 3 4 5 6 7 8 9
5 6 7 8 9
5 8 11 14 17
*///:~
The range( ) method has been overloaded, which means the same method name can be
used with different argument lists (you’ll learn about overloading soon). The first overloaded
form of range( ) just starts at zero and produces values up to but not including the top end
of the range. The second form starts at the first value and goes until one less than the second,
and the third form has a step value so it increases by that value. range( ) is a very simple
version of what’s called a generator, which you’ll see later in the book.
Note that although range( ) allows the use of the foreach syntax in more places, and thus
arguably increases readability, it is a little less efficient, so if you are tuning for performance
you may want to use a profiler, which is a tool that measures the performance of your code.
You’ll note the use of printnb( ) in addition to print( ). The printnb( ) method does not
emit a newline, so it allows you to output a line in pieces.
p.104 swith
jdk7 对switch 字符串的支持
In the JDK 7 release, you can use a String
object in the expression of a switch
statement:
- public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
- String typeOfDay;
- switch (dayOfWeekArg) {
- case "Monday":
- typeOfDay = "Start of work week";
- break;
- case "Tuesday":
- case "Wednesday":
- case "Thursday":
- typeOfDay = "Midweek";
- break;
- case "Friday":
- typeOfDay = "End of work week";
- break;
- case "Saturday":
- case "Sunday":
- typeOfDay = "Weekend";
- break;
- default:
- throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
- }
- return typeOfDay;
- }