jdk1.5以后几点新特性

以前对jdk1.5后的一些新用法不感冒,现在发现就新式for-each来看,功能实现了,而代码更优雅:

package com.duben.spring.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ForTest
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

/**
* 旧式写法
*/
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
/**
* 新式写法
*/
for (int a : arr)
System.out.println(a);

String arr2[] = {"真","好","用","!!"};
for(String a2 : arr2)
System.out.println(a2);

int arr3[][] = {{1,2,3},{4,5,6,},{7,8,9}};
for(int a31[] : arr3)
{
for(int a32 : a31)
{
System.out.println(a32);
}
System.out.println();
}

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
/**
* 根据集合类长度遍历
*/
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
/**
* 根据迭代器遍历
*/
for(Iterator i = list.iterator();i.hasNext();)
{
System.out.println(i.next());
}
/**
* 根据新式for-each遍历
*/
for(String element : list)
{
System.out.println(element);
}
}
}


除此之外,还有一些新特性,简要列举出来:
以下来自CSDN博客,出处:[url]http://blog.csdn.net/touchSea/archive/2006/09/11/1210425.aspx[/url]
1. 自动装箱与拆箱 对应C#
例1.1
Integer i = 10; 
int j = i; //隐匿地把基本类型int转换为Integer对象

2.加泛型 对应C++模板
import java.util.*; 

ArrayList<String> animals = new ArrayList<String>();
animals.add("Dog");
animals.add("Cat");
animals.add("Chick");
animals.add("Cow");
for(String option : animals) {
System.out.println(option);
}


3.参数可变的方法和printf
例3.1
定义:
public int sum(int... n) { //传过来n为一个int型数组 
int tempSum;
for(int option : n) {
tempSum+=option;
}
/*
for(int i = 0; i < n.length; i++) {
tempSum+=n[i];
}
*/
return tempSum;
}
调用1: sum(1);
调用2: sum(1,2);
调用3: sum(1,2,3,4);

例3.2 printf方法, 对应c语言的printf
int x = 10; 
int y = 20;
int sum = x + y;
System.out.printf("%d + %d = %d",x,y,sum);


4. 枚举
例4.1
public enum MyColors { 
red,
black,
blue,
green,
yellow
}

MyColors color = MyColors.red;
for(MyColors option : color.values()) {
System.out.println(option);
}

/**不能在switch语句里这样写case MyColors.red:
*这样编译器不会让你通过*/
switch(color) {
case red: System.out.println("best color is "+red); break;
case black: System.out.println("NO " + black); break;
default:
System.out.println("What");
break;
}

5.静态引用
例5.1
1.5版本以前的写法是:

  
import java.lang.Math; //程序开头处 

  ...

  double x = Math.random();

1.5版本中可以这样写
import static java.lang.Math.random; //程序开头处 

...
  
double x = random();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值