Java 7

比較容易忘記的特色

Diamond Operator

Diamond Operator

Map<String,List<String>> anagrams = new HashMap<String,List<String>>();


// Dimanod 

Map<String,List<String>> anagrams = new HashMap<>();

Switch 裡面

可以使用字串

Switch 裡面 可以使用字串

  // Jobd is match 領班(101), 組長(102), 助理(214)
  if ("101".equals(userEjobd)) {
      jobdCheck = true;
  } else if ("102".equals(userEjobd)) {
      jobdCheck = true;
  } else if ("214".equals(userEjobd)) {
      jobdCheck = true;
  }

Switch 裡面 可以使用字串

switch(userEjobd) {
    case "101":
    case "102":
    case "214":
       jobdCheck = true;
}

Switch 裡面 可以使用字串

public class Test  
{ 
    public static void main(String[] args) 
    { 
        String str = "two"; 
        switch(str) 
        { 
            case "one": 
                System.out.println("one"); 
                break; 
            case "two": 
                System.out.println("two"); 
                break; 
            case "three": 
                System.out.println("three"); 
                break; 
            default: 
                System.out.println("no match"); 
        } 
    } 
} 

自動資源管理

Try-with-resource

自動資源管理

    public static void main(String[] args) {

        BufferedReader br = null;
        String line;

        try {

            br = new BufferedReader(new FileReader("C:\\testing.txt"));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

自動資源管理

    public static void main(String[] args) {

        String line;

        try (BufferedReader br = new BufferedReader(
                new FileReader("C:\\testing.txt"))) {

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

		// br will be closed automatically
    }

帶底線的數字表現形式

帶底線的數字表現形式

int thousand =  1_000;

int million  =  1_000_000

串起來的 Exception

串起來的 Exception

   public voidoldMultiCatch() {

            try{

                  methodThatThrowsThreeExceptions();

            } catch(ExceptionOne e) {

                  // log and deal with ExceptionOne

            } catch(ExceptionTwo e) {

                  // log and deal with ExceptionTwo

            } catch(ExceptionThree e) {

                  // log and deal with ExceptionThree

            }

      }

串起來的 Exception

     public voidnewMultiCatch() {

            try{

                  methodThatThrowsThreeExceptions();

            } catch(ExceptionOne | ExceptionTwo | ExceptionThree e) {

                  // log and deal with all Exceptions

            }

      }

Java 7 比較容易忘記的特色

By Balicanta Yao

Java 7 比較容易忘記的特色

  • 107