Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Out with the Old, In with the New

Tags:

java

Enums. Replacing

public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;

with

public enum Suit { 
  CLUBS, 
  DIAMONDS, 
  HEARTS, 
  SPADES 
}

Generics and no longer needing to create an iterator to go through all elements in a collection. The new version is much better, easier to use, and easier to understand.

EDIT:

Before:

List l = someList;
Iterator i = l.getIterator();
while (i.hasNext()) {
    MyObject o = (MyObject)i.next();
}

After

List<MyObject> l = someList;
for (MyObject o : l) {
    //do something
}

Using local variables of type StringBuffer to perform string concatenation. Unless synchronization is required, it is now recommended to use StringBuilder instead, because this class offers better performance (presumably because it is unsynchronized).


reading a string from standard input:

Java pre-5:

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String str = reader.readLine();
    reader.close();
}
catch (IOException e) {
    System.err.println("error when closing input stream.");
}

Java 5:

Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
reader.close();

Java 6:

Console reader = System.console();
String str = reader.readLine();

Here is one that I see:

String.split() versus StringTokenizer.

StringTokenizer is not recommended for new code, but I still see people use it.

As for compatibility, Sun makes a huge effort to have Java be backwards and forwards compatible. That partially accounts for why generics are so complex. Deprecation is also supposed to help ease transitions from old to new code.


Older code using Thread instead of the many other alternatives to Thread... these days, very little of the code I run across still needs to use a raw thread. They would be better served by a level of abstraction, particular Callable/Futures/Executors.

See:

java.util.Timer

javax.swing.Timer

java.util.concurrent.*