【新特性】JDK1.7

 一、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 ;
}

二、"<>"这个玩意儿的运用List<String> tempList = new ArrayList<>(); 即泛型实例化类型自动推断。

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

}

 

三、自定义自动关闭类

以下是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 == )
                return;
            in.close();
            in = ;
            cb = ;
        }
    }

 

四、新增一些取环境信息的工具方法

File System.getJavaIoTempDir() // IO临时文件夹

File System.getJavaHomeDir() // JRE的安装目录

File System.getUserHomeDir() // 当前用户目录

File System.getUserDir() // 启动java进程时所在的目录

.......

 

五、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)

 

六、 两个char间的equals

boolean Character.equalsIgnoreCase(char ch1, char ch2)

 

七、安全的加减乘除

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集合中获取对象

 

九、数值可加下划线

int one_million = 1_000_000;
 

十、支持二进制文字

int binary = 0b1001_1001;
 

十一、简化了可变参数方法的调用

当试图使用一个不可具体化的可变参数并调用一个*varargs* (可变)方法时,编辑器会生成一个“非安全操作”的警告。

十二、在try catch异常扑捉中,一个catch可以写多个异常类型,用"|"隔开

jdk7之前:

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

jdk7例子如下

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

 

十三、jdk7之前,你必须用try{}finally{}在try内使用资源,在finally中关闭资源,不管try中的代码是否正常退出或者异常退出。jdk7之后,你可以不必要写finally语句来关闭资源,只要你在try()的括号内部定义要使用的资源

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 = ;
      BufferedWriter out = ;
      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 != ) in.close();
            if (out != ) 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();
      }
   }
}

 

猜你喜欢

转载自www.cnblogs.com/sunny3096/p/10373358.html
0条评论
添加一条新回复