java--各個版本主要新特性


JDK1.5新特性:

 1.自動裝箱與拆箱

自動裝箱,只需將該值賦給一個類型包裝器引用,java會自動創建一個對象。
自動拆箱,只需將該對象值賦給一個基本類型即可。
java——類的包裝器
類型包裝器有:Double,Float,Long,Integer,Short,Character和Boolean
2.枚舉
把集合里的對象元素一個一個提取出來。枚舉類型使代碼更具可讀性,理解清晰,易於維護。枚舉類型是強類型的,從而保證了系統安全性。
而以類的靜態字段實現的類似替代模型,不具有枚舉的簡單性和類型安全性。 簡單的用法:JavaEnum簡單的用法一般用於代表一組常用常量,可用來代表一類相同類型的常量值。 復雜用法:Java為枚舉類型提供了一些內置的方法,同事枚舉常量還可以有自己的方法。可以很方便的遍歷枚舉對象。
3.靜態導入
通過使用 import static,就可以不用指定 Constants 類名而直接使用靜態成員,包括靜態方法。
import xxxx 和 import static xxxx的區別是前者一般導入的是類文件如import java.util.Scanner;
后者一般是導入靜態的方法,import static java.lang.System.out。
4.可變參數(Varargs)
/**可變參數本質就是一個數組,arr就是一個數組的引用地址(反編譯工具查看源代碼)

一個方法 可以有可變參數和普通參數,但是可變參數必須放到參數列表末尾;

一個方法 有且只能有一個可變參數;
**/
public int getSum(int value,int … arr){

}
5.內省(Introspector)
是 Java語言對Bean類屬性、事件的一種缺省處理方法。例如類A中有屬性name,那我們可以通過getName,setName來得到其值或者設置新 的值。
通過getName/setName來訪問name屬性,這就是默認的規則。Java中提供了一套API用來訪問某個屬性的getter /setter方法,通過這些API可以使你不需要了解這個規則(但你最好還是要搞清楚),
這些API存放於包java.beans中。一般的做法是通過類Introspector來獲取某個對象的BeanInfo信息,然后通過BeanInfo來獲取屬性的描述器 (PropertyDescriptor),通過這個屬性描述器就
可以獲取某個屬性對應的getter
/setter方法,然后我們就可以通過反射機制來 調用這些方法。
6.泛型(Generic) 
C++ 通過模板技術可以指定集合的元素類型,而Java在1.5之前一直沒有相對應的功能。一個集合可以放任何類型的對象,相應地從集合里面拿對象的時候我們也 不得不對他們進行強制得類型轉換。
引入了泛型,它允許指定集合里元素的類型,這樣你可以得到強類型在編譯時刻進行類型檢查的好處。
7.For-Each循環 
For-Each循環得加入簡化了集合的遍歷。假設我們要遍歷一個集合對其中的元素進行一些處理。

JDK 1.6新特性

 暫無

JDK 1.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. 泛型實例化類型自動推斷。

// Pre-JDK 7
List<String> lst1 = new ArrayList<String>();
// JDK 7 supports limited type inference for generic instance creation
List<String> lst2 = new ArrayList<>();

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. 新增一些取環境信息的工具方法

FileSystem.getJavaIoTempDir() // IO臨時文件夾

FileSystem.getJavaHomeDir() // JRE的安裝目錄

FileSystem.getUserHomeDir() // 當前用戶目錄

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

.......

5. try(){ } catch(){}資源自動關閉

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();
      }
   }
}

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

//jdk7 以前
try {
   ......
} catch(ClassNotFoundException ex) {
   ex.printStackTrace();
} catch(SQLException ex) {
   ex.printStackTrace();
}

//jdk7例子如下

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

JDK8十大特性

1.Lambda表達式

public void testLambda(){
      List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);  
      list.forEach(System.out::println);
      list.forEach(e -> System.out.println("方式二:"+e));
}

2.Stream函數式操作流元素集合

public void testStream(){
     List<Integer> nums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10);
     System.out.println(
        nums.stream()//轉成Stream
        .filter(team -> team!=null)//過濾
        .distinct()//去重
        .mapToInt(num->num*2)//map操作
        .skip(2)//跳過前2個元素
        .limit(4)//限制取前4個元素
        .peek(System.out::println)//流式處理對象函數
        .sum()//求和
    );
}

3.接口新增:默認方法與靜態方法

 public interface JDK8Interface1 {
  
      //1.接口中可以定義靜態方法了
      public static void staticMethod(){
          System.out.println("接口中的靜態方法");
      }
      
      //2.使用default之后就可以定義普通方法的方法體了
      public default void defaultMethod(){
         System.out.println("接口中的默認方法");
     }
 }

4.方法引用,與Lambda表達式聯合使用

    public void testMethodReference(){
         //構造器引用。語法是Class::new,或者更一般的Class< T >::new,要求構造器方法是沒有參數;
         final Car car = Car.create( Car::new );
         final List< Car > cars = Arrays.asList( car );
         //靜態方法引用。語法是Class::static_method,要求接受一個Class類型的參數;
         cars.forEach( Car::collide );
         //任意對象的方法引用。它的語法是Class::method。無參,所有元素調用;
         cars.forEach( Car::repair );
         //特定對象的方法引用,它的語法是instance::method。有參,在某個對象上調用方法,將列表元素作為參數傳入;
         final Car police = Car.create( Car::new );
         cars.forEach( police::follow );
     }
     
     public static class Car {
         public static Car create( final Supplier< Car > supplier ) {
             return supplier.get();
         }              
              
         public static void collide( final Car car ) {
             System.out.println( "靜態方法引用 " + car.toString() );
         }
              
         public void repair() {   
             System.out.println( "任意對象的方法引用 " + this.toString() );
         }
         
         public void follow( final Car car ) {
             System.out.println( "特定對象的方法引用 " + car.toString() );
         }
     }

5.引入重復注解

6.類型注解

7.最新的Date/Time API (JSR 310)

8.新增base64加解密API

     public void testBase64(){
         final String text = "就是要測試加解密!!abjdkhdkuasu!!@@@@";
         String encoded = Base64.getEncoder()
             .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
         System.out.println("加密后="+ encoded );
          
         final String decoded = new String( 
             Base64.getDecoder().decode( encoded ),
             StandardCharsets.UTF_8 );
         System.out.println( "解密后="+decoded );
     }

9.數組並行(parallel)操作

     public void testParallel(){
         long[] arrayOfLong = new long [ 20000 ];        
         //1.給數組隨機賦值
         Arrays.parallelSetAll( arrayOfLong, 
             index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
         //2.打印出前10個元素
         Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
             i -> System.out.print( i + " " ) );
         System.out.println();
         //3.數組排序
         Arrays.parallelSort( arrayOfLong );     
         //4.打印排序后的前10個元素
         Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
             i -> System.out.print( i + " " ) );
         System.out.println();
     }

10.JVM的PermGen空間被移除:取代它的是Metaspace(JEP 122)元空間

//-XX:MetaspaceSize初始空間大小,達到該值就會觸發垃圾收集進行類型卸載,同時GC會對該值進行調整
//-XX:MaxMetaspaceSize最大空間,默認是沒有限制
//-XX:MinMetaspaceFreeRatio在GC之后,最小的Metaspace剩余空間容量的百分比,減少為分配空間所導致的垃圾收集
//-XX:MaxMetaspaceFreeRatio在GC之后,最大的Metaspace剩余空間容量的百分比,減少為釋放空間所導致的垃圾收集

 


免責聲明!

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



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