Java: Out with the Old, In with the New

后端 未结 30 1953
遥遥无期
遥遥无期 2020-12-22 16:11

Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, whe

相关标签:
30条回答
  • 2020-12-22 16:35

    Converting a number to a String:

    String s = n + "";
    

    In this case I think there has always been a better way of doing this:

    String s = String.valueOf(n);
    
    0 讨论(0)
  • 2020-12-22 16:35

    It is worth noting that Java 5.0 has been out for five years now and there have only been minor changes since then. You would have to be working on very old code to be still refactoring it.

    0 讨论(0)
  • 2020-12-22 16:36

    I'm a little wary to refactor along these lines if that is all you are doing to your source tree. The examples so far do not seem like reasons alone to change any working code base, but maybe if you are adding new functionality you should take advantage of all the new stuff.

    At the end of the day, these example are not really removing boiler plate code, they are just using the more manageable constructs of newer JDKs to make nice looking boiler plate code.

    Most ways to make your code elegant are not in the JDK.

    0 讨论(0)
  • 2020-12-22 16:42

    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();
    
    0 讨论(0)
  • 2020-12-22 16:42

    Improved singleton patterns. Technically these are covered under the popular answer enums, but it's a significant subcategory.

    public enum Singleton {
        INSTANCE;
    
        public void someMethod() {
            ...
        }
    }
    

    is cleaner and safer than

    public class Singleton {
        public static final Singleton INSTANCE = new Singleton();
    
        private Singleton() {
            ...
        }
    
        public void someMethod() {
            ...
        }
    }
    
    0 讨论(0)
  • 2020-12-22 16:43

    Generic collections make coding much more bug-resistant. OLD:

    Vector stringVector = new Vector();
    stringVector.add("hi");
    stringVector.add(528); // oops!
    stringVector.add(new Whatzit());  // Oh my, could spell trouble later on!
    

    NEW:

    ArrayList<String> stringList = new ArrayList<String>();
    stringList.add("hello again");
    stringList.add(new Whatzit()); // Won't compile!
    
    0 讨论(0)
提交回复
热议问题