1. 程式人生 > >jdk7常用新特性

jdk7常用新特性

switch可以使用字串來判斷

String s = "test";
switch (s) {
    case "test" :
       System.out.println("test");
       break;
    case "test1" :
        System.out.println("test1");
        break ;
    default :
      System.out.println("break");
      break ;
}

使用泛型時右邊的泛型可省略不寫

//pre jdk7
List<String> list=new ArrayList<String>();

//after jdk7
List<String> list= new ArrayList<>();

集合操作的增強

//pre jdk7
List<String> list=new ArrayList<String>();
list.add("item"); 
String Item=list.get(0); 

Set<String> set=new HashSet<String>();
set.add("item"); 

Map<String,Integer> map=new HashMap<String,Integer>();
map.put("key",1); 
int value=map.get("key");


//after jdk7
List<String> list=["item"];           //建立List集合
String item=list[0];                  //取出集合中第一個元素
    
Set<String> set={"item"};             //建立set集合

Map<String,Integer> map={"key":1};    //建立map集合
int value=map["key"];                 //根據key取值

 

try-with-resources

try{}catch(){}finally{}形式變為try(){}catch{}形式,不需要進行流的關閉,自動關閉流

//pre jdk7
public static void main(String[] args) {
      BufferedReader in = null;
      BufferedWriter out = null;
      try {
         in  = new BufferedReader(new FileReader("in.txt"));
         out = new BufferedWriter(new FileWriter("out.txt"));
         int charRead;
         while ((charRead = in.read()) != -1) {
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {            // always close the streams
         try {
            if (in != null) in.close();
            if (out != null) out.close();
         } catch (IOException ex) {
            ex.printStackTrace();
         }
      }
}

//after jdk7
 public static void main(String[] args) {
      try (BufferedReader in  = new BufferedReader(new FileReader("in.txt"));
           BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))) {
         int charRead;
         while ((charRead = in.read()) != -1) {
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }

新增了Objects類

提供了一些方法來操作object物件,大多數都是針對空指標安全的

 

jdk8的新特性基本就是stream的運用,另一篇部落格有詳細的描述=======》地址傳送門在此