HTML/JavaScript小工具

HTML/JavaScript小工具

2012年9月20日 星期四

Java7新功能整理之一


Java 7
新功能整理之一
一 switch 新增 String 作為條件 但要注意 String為Null,與字串大小寫
二 數字可使用Using underscores (_) 如 flaot value1 = 123_56.178_22f
小心如下錯誤寫法
 long productKey = _12345_67890_09876_54321L;
   float pi = 3._14_15F;
   long licenseNumber = 123_456_789_L;

三 Using the try-with-resources block:過去使用資源後需要自行關閉現在會自動關閉(Automated Resource Management)
Files 出於java新版的套件 java.nio.file.Files;
 try (BufferedReader inputReader = Files.newBufferedReader(
                        Paths.get(new URI ("file:///C:/home/docs/users.txt")),
                        Charset.defaultCharset());
                BufferedWriter outputWriter = Files.newBufferedWriter(
                        Paths.get(new URI("file:///C:/home/docs/users.bak")),
                        Charset.defaultCharset())) {
            String inputLine;
            while ((inputLine = inputReader.readLine()) != null) {
                outputWriter.write(inputLine);
                outputWriter.newLine();}
            System.out.println("Copy complete!");}
catch (URISyntaxException | IOException ex) {
            ex.printStackTrace();
}
也可自行實作一個ARM物件,需實作AutoCloseable

四 multiple exception:
public class MultipleExceptions {
    private static final Logger logger = Logger.getLogger("log.
txt");
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        try {
            Scanner scanner = new Scanner(System.in);
            int number = scanner.nextInt();
            if (number < 0) {
                throw new InvalidParameter();
}
            System.out.println("The number is: " + number);
}
catch (InputMismatchException | InvalidParameter e) {
            logger.log(Level.INFO, "Invalid input, try again");
}
}
要注意
1 使用Multiple Exceptions 不可將其父類別至於選項中如(InputMismatchException | Exception e)
2 catch 內的變數不可再重新指向
3 Java 7 多了一個AssertionError 實體

五 Using the diamond operator <>
過去  List<String> list = new ArrayList(); 會出現警告訊息
現在可改成List<String> list = new ArrayList<>();即可
如不想發出警告可使用
@SuppressWarnings({ "unused", "unchecked", "rawtypes" })

@SafeVarargs 方法使用範形不想發出警告,最好用於方法變數是reifiable Type

沒有留言:

張貼留言