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的运用,另一篇博客有详细的描述=======》地址传送门在此

猜你喜欢

转载自blog.csdn.net/lidai352710967/article/details/82597433