Books
in black and white
Main menu
Share a book About us Home
Books
Biology Business Chemistry Computers Culture Economics Fiction Games Guide History Management Mathematical Medicine Mental Fitnes Physics Psychology Scince Sport Technics
Ads

More Java Pitfalls Share Reactor - Daconta M,C.

Daconta M,C. More Java Pitfalls Share Reactor - Wiley publishing, 2003. - 476 p.
ISBN: 0-471-23751-5
Download (direct link): morejavapitfallssharereactor2003.pdf
Previous << 1 .. 54 55 56 57 58 59 < 60 > 61 62 63 64 65 66 .. 166 >> Next

Out of these three issues, we can currently only fix the proper way to delete a file after a successful rename, as Listing 20.2 demonstrates. Because the other two issues result from Java's design, only the Java Community Process (JCP) can initiate these fixes.
01 package org.javapitfalls.item20;
02
03 import java.io.*;
04
05 public class GoodFileRename
06 {
Listing 20.2 GoodFileRename.java (continued)
156 Item 20
07 public static void main(String args[])
08 {
09 try
10 {
11 // check if test file in current dir
12 File f = new File("dummy2.txt");
13 String name = f.getName();
14 if (f.exists())
15 System.out.println(f.getName() + " exists.");
16 else
17 System.out.println(f.getName() + 2
" does not exist.");
18
19 // Attempt to rename with a different extension
20 int dotldx = name.indexOf('.');
21 if (dotldx >= 0)
22 name = name.substring(0, dotldx);
23 name = name + ".tst";
24 String path = f.getAbsolutePath();
25 int lastSep = path.lastlndexOf(File.separator);
26 if (lastSep > 0)
27 path = path.substring(0,lastSep);
28 System.out.println("path: " + path);
29 File f3 = new File(path + File.separator + name);
30 System.out.println("new name: " + f3.getPath());
31 if (f.renameTo(f3))
32 System.out.println(
33 "Rename to new extension Successful.");
34 else
35 System.out.println(
36 "Rename to new extension failed.");
37
38 // delete the file
39 // Fix 1: delete via the "Filename" not File
40 if (f3.delete())
41 System.out.println("Delete Successful.");
42 else
43 System.out.println("Delete Failed.");
44 } catch (Throwable t)
45 {
46 t.printStackTrace();
47 }
48 }
49 }
50
Listing 20.2 (continued)
Use Iteration over Enumeration 157
A run of Listing 20.2 produces the following output:
E:\classes\org\javapitfalls\Item20> java org.javapitfalls.item20 2
.GoodFileRename
dummy2.txt exists.
path: E:\classes\org\javapitfalls\Item20
new name: E:\classes\org\javapitfalls\Item20\dummy2.tst
Rename to new extension Successful.
Delete Successful.
Thus, don't use the File class as if it represents a file instead of the filename. With that in mind, once the file is renamed, operations such as delete() only work on the new filename.
Item 21: Use Iteration over Enumeration11
Enumeration is the original interface, available since JDK 1.0, to iterate over (step through) all the elements in a collection. In terms of semantics, it would have been better to call the interface "Enumerator," as it expresses the role a class is "putting on" by implementing the interface, instead of "Enumeration," which specifies an occurrence of the activity. This is in line with all the more recent interfaces in the java.util package like Observer, Comparator, and Iterator. Table 21.1 compares the Enumeration interface to the Iterator interface.
Table 21.1 Enumeration versus Iterator
ENUMERATION METHODS DESCRIPTION ITERATOR METHODS DESCRIPTION
boolean hasMoreElements() Checks if this ; enumeration has more elements. boolean hasNext() Checks if this iterator has more elements.
Object nextElement(); Returns the next element in the enumeration if there is at least 1 more. Object next() i Returns the next element in the iterator if there is at least one more.
void remove() Removes from
the underlying collection the last element returned. (optional)
11 This pitfall was first published by JavaWorld (www.javaworld.com) in the article, "Practice makes perfect" November 2001, (http://www.javaworld.com/javaworld/jw-11-2001/jw-1116-traps-p2 .html) and is reprinted here with permission. The pitfall has been updated from reader feedback.
158 Item 21
The idiom for using both an Enumeration and Iterator is the same:
while (i.hasNext())
{
Object o = i.next();
// do something with o
}
As is evident in Table 21.1, both Iterator and Enumeration are functionally identical except for two differences:
¦¦ Iterators allow you to safely remove an element from the underlying collection in a well-defined way.
¦¦ The iterator method names have been simplified.
There is a removal of elements pitfall in the Enumeration implementation class of Vector where its behavior differs from Iteration. Listing 21.1 demonstrates the behavior in question.
01 package org.javapitfalls.item21;
02
03 import java.util.*;
04
05 public class BadVisitor
06 {
07 public static void main(String args[])
08 {
09 Vector v = new Vector();
10 v.add("one"); v.add("two"); v.add("three"); v.add("four");
11
12 Enumeration enum = v.elements();
13 while (enum.hasMoreElements())
14 {
15 String s = (String) enum.nextElement();
16 if (s.equals("two"))
17 v.remove("two");
18 else
19 {
20 // Visit
21 System.out.println(s);
22 }
23 }
24
25 // see what's left
Listing 21.1 BadVisitor.java
Use Iteration over Enumeration 159
26 System.out.println("What’s really there...");
Previous << 1 .. 54 55 56 57 58 59 < 60 > 61 62 63 64 65 66 .. 166 >> Next