jdk1.7新特性


1,switch中可以使用字串了

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

2,"<>"這個玩意兒的運用List<String> tempList = new ArrayList<>(); 即泛型實例化類型自動推斷。

import java.util.*;
public class JDK7GenericTest {
   public static void main(String[] args) {
      // Pre-JDK 7
      List<String> lst1 = new ArrayList<String>();
      // JDK 7 supports limited type inference for generic instance creation
      List<String> lst2 = new ArrayList<>();
 
      lst1.add("Mon");
      lst1.add("Tue");
      lst2.add("Wed");
      lst2.add("Thu");
 
      for (String item: lst1) {
         System.out.println(item);
      }
 
      for (String item: lst2) {
         System.out.println(item);
      }
   }
}

3. 自定義自動關閉類

以下是jdk7 api中的接口,(不過注釋太長,刪掉了close()方法的一部分注釋)

/**
 * A resource that must be closed when it is no longer needed.
 *
 * @author Josh Bloch
 * @since 1.7
 */
public interface AutoCloseable {
    /**
     * Closes this resource, relinquishing any underlying resources.
     * This method is invoked automatically on objects managed by the
     * {@code try}-with-resources statement.
     *
     */
    void close() throws Exception;
}

只要實現該接口,在該類對象銷毀時自動調用close方法,你可以在close方法關閉你想關閉的資源,例子如下

class TryClose implements AutoCloseable {

 @Override
 public void close() throw Exception {
  System.out.println(" Custom close method …
                                         close resources ");
 }
}
//請看jdk自帶類BufferedReader如何實現close方法(當然還有很多類似類型的類)

  public void close() throws IOException {
        synchronized (lock) {
            if (in == null)
                return;
            in.close();
            in = null;
            cb = null;
        }
    }

4. 新增一些取環境信息的工具方法


File System.getJavaIoTempDir() // IO臨時文件夾

File System.getJavaHomeDir() // JRE的安裝目錄

File System.getUserHomeDir() // 當前用戶目錄

File System.getUserDir() // 啟動java進程時所在的目錄

 


.......

5. Boolean類型反轉,空指針安全,參與位運算

Boolean Booleans.negate(Boolean booleanObj)

True => False , False => True, Null => Null

boolean Booleans.and(boolean[] array)

boolean Booleans.or(boolean[] array)

boolean Booleans.xor(boolean[] array)

boolean Booleans.and(Boolean[] array)

boolean Booleans.or(Boolean[] array)

boolean Booleans.xor(Boolean[] array)

 

6. 兩個char間的equals

boolean Character.equalsIgnoreCase(char ch1, char ch2)


7,安全的加減乘除

int Math.safeToInt(long value)

int Math.safeNegate(int value)

long Math.safeSubtract(long value1, int value2)

long Math.safeSubtract(long value1, long value2)

int Math.safeMultiply(int value1, int value2)

long Math.safeMultiply(long value1, int value2)

long Math.safeMultiply(long value1, long value2)

long Math.safeNegate(long value)

int Math.safeAdd(int value1, int value2)

long Math.safeAdd(long value1, int value2)

long Math.safeAdd(long value1, long value2)

int Math.safeSubtract(int value1, int value2)

對Java集合(Collections)的增強支持

在JDK1.7之前的版本中,Java集合容器中存取元素的形式如下:

以List、Set、Map集合容器為例:

//創建List接口對象
    List<String> list=new ArrayList<String>();
    list.add("item"); //用add()方法獲取對象
    String Item=list.get(0); //用get()方法獲取對象

 

    //創建Set接口對象
    Set<String> set=new HashSet<String>();
    set.add("item"); //用add()方法添加對象

 

    //創建Map接口對象
    Map<String,Integer> map=new HashMap<String,Integer>();
    map.put("key",1); //用put()方法添加對象
    int value=map.get("key");

在JDK1.7中,摒棄了Java集合接口的實現類,如:ArrayList、HashSet和HashMap。而是直接采用[]、{}的形式存入對象,采用[]的形式按照索引、鍵值來獲取集合中的對象,如下:

    

  List<String> list=["item"]; //向List集合中添加元素
      String item=list[0]; //從List集合中獲取元素

      Set<String> set={"item"}; //向Set集合對象中添加元素

      Map<String,Integer> map={"key":1}; //向Map集合中添加對象
      int value=map["key"]; //從Map集合中獲取對象

3.數值可加下划線

例如:

int one_million = 1_000_000;

4.支持二進制文字

例如:

int binary = 0b1001_1001;

 5.簡化了可變參數方法的調用

當程序員試圖使用一個不可具體化的可變參數並調用一個*varargs* (可變)方法時,編輯器會生成一個“非安全操作”的警告。

6、在try catch異常撲捉中,一個catch可以寫多個異常類型,用"|"隔開,

jdk7之前:

try {
   ......
} catch(ClassNotFoundException ex) {
   ex.printStackTrace();
} catch(SQLException ex) {
   ex.printStackTrace();
}

jdk7例子如下

try {
   ......
} catch(ClassNotFoundException|SQLException ex) {
   ex.printStackTrace();
}

 

7、jdk7之前,你必須用try{}finally{}在try()內使用資源,在finally中關閉資源,不管try中的代碼是否正常退出或者異常退出。jdk7之后,你可以不必要寫finally語句來關閉資源,只要你在try()的括號內部定義要使用的資源。

前提是try()內的那些資源要實現自定義自動關閉類,這是新特性 

try-with-resources statement。

請看例子:

jdk7之前

import java.io.*;
// Copy from one file to another file character by character.
// Pre-JDK 7 requires you to close the resources using a finally block.
public class FileCopyPreJDK7 {
   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) {
            System.out.printf("%c ", (char)charRead);
            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();
         }
      }
 
      try {
         in.read();   // Trigger IOException: Stream closed
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

jdk7之后

import java.io.*;
// Copy from one file to another file character by character.
// JDK 7 has a try-with-resources statement, which ensures that
// each resource opened in try() is closed at the end of the statement.
public class FileCopyJDK7 {
   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) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}
 

JAVA7新增加了Objects類

 它提供了一些方法來操作對象,這些方法大多數是“空指針”安全的,比如 Objects.toString(obj);如果obj是null,,則輸出是null。

否則如果你自己用obj.toString(),如果obj是null,則會拋出NullPointerException.

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM