Java7にキャッチアップ
TopCoderやAtCoderでもJava7が使えるようになったことだし、止まっている知識をアップデートする。
Java7の新機能について、気になるものをこのあたりから拾ってきて試した。
http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html
Binary Literals
2進数リテラル。先頭に0b(または0B)を付ける。
int one = 0b00000001; int two = 0b00000010; int four = 0b00000100; int FF = 0b11111111; System.out.println(Integer.toBinaryString(FF ^ (one | two | four)));
出力
11111000
Underscores in Numeric Literals
数値リテラルの中にアンダースコアを含ませることができる。
System.out.println(123_456_789);
System.out.println(3.141_592_653_589_793);
Strings in switch Statements
switch文でStringが使えるようになった。
switch (args[0]) { case "-n": int n = Integer.parseInt(args[1]); break; case "-h": System.out.println("usage: hogehoge"); break; case "-v": System.out.println("version 3.14"); break; default: break; }
if-then-elseより速いらしい
try-with-resources, AutoCloseable
try-catch-finallyを使わずにリソース自動解放
try (Scanner sc = new Scanner(System.in)) { System.out.println(sc.nextInt()); }
tryの中にはAutoCloseableインターフェースを実装したクラスを指定する。
Type Inference for Generic Instance Creation
ジェネリックなクラスの初期化でコンストラクタに型パラメータを指定しなくて良くなる
ArrayList<Integer> list = new ArrayList<>(); HashMap<String, Integer> map = new HashMap<>();
java.nio.fileパッケージ
http://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html
FilesクラスとかPathクラスとか、ファイル操作まわりに便利なライブラリが追加されている。
FileSystem fileSystem = FileSystems.getDefault(); Path src = fileSystem.getPath("./tmp.txt"); Path dst = fileSystem.getPath("./copyTo.txt"); try { Files.copy(src, dst); Files.delete(src); for (String line : Files.readAllLines(dst, Charset.forName("UTF-8"))) { System.out.println(line); } } catch (IOException e) { System.err.println(e); }
Objectsクラス
http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
小物関数群。
int hash = Objects.hash("string", 42, 3.14); String str = "hoge"; String nullStr = null; Objects.equals(str, nullStr); System.out.println(Objects.toString(nullStr, "this object is NULL!!!!"));
BitSet
http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html
微妙にメソッドが追加されていた。
BitSet bitset = BitSet.valueOf(new long[] { 0xFFFF_FFFF_FFFF_FFFFL, 0x1234_5678_9ABC_DEF0L }); for (int i = bitset.previousSetBit(bitset.size()); i >= 0; i = bitset.previousSetBit(i - 1)) { System.out.println(i); } byte[] bytes = bitset.toByteArray();
Integer#compare
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29
自分で比較コードを書かなくて良くなった。
Longなどでも同じ。Doubleには前からあった
Integer.compare(0, 0); Long.compare(Long.MAX_VALUE, Long.MIN_VALUE);