Java: Out with the Old, In with the New

后端 未结 30 1956
遥遥无期
遥遥无期 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:32

    Using local variables of type Vector to hold a list of objects. Unless synchronization is required, it is now recommended to use a List implementation such as ArrayList instead, because this class offers better performance (because it is unsynchronized).

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

    Changing JUnit 3-style tests:

    class Test extends TestCase {
        public void testYadaYada() { ... }
    }
    

    to JUnit 4-style tests:

    class Test {
       @Test public void yadaYada() { ... }
    }
    
    0 讨论(0)
  • 2020-12-22 16:34

    Explicit conversion between primitive and wrapper types (e.g. Integer to int or vice versa) which is taken care of automatically by autoboxing/unboxing since Java 1.5.

    An example is

    Integer myInteger = 6;
    int myInt = myInteger.intValue();
    

    Can simply be written as

    Integer myInteger = 6;
    int myInt = myInteger;
    

    But watch out for NullPointerExceptions :)

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

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

    Formatted printing was introduced as late as in JDK 1.5. So instead of using:

    String str = "test " + intValue + " test " + doubleValue;
    

    or the equivalent using a StringBuilder,

    one can use

    String str = String.format("test %d test %lg", intValue, doubleValue);
    

    The latter is much more readable, both from the string concatenation and the string builder versions. Still I find that people adopt this style very slowly. Log4j framework for example, doesn't use this, although I believe it would be greatly benefited to do so.

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

    A simple change in since 1.5 but makes a small difference - in the Swing API accessing the contentPane of a JFrame:

    myframe.getContentPane().add(mycomponent);
    

    becomes

    myframe.add(mycomponent);
    

    And of course the introduction of Enums has changed the way many applications that used constants in the past behave.

    String.format() has greatly improved String manipulation and the ternary if statement is quite helpful in making code easier to read.

    0 讨论(0)
提交回复
热议问题