JDK核心API:Java1.5语言新特性简单总结

翻译|其它|编辑:郝浩|2008-01-16 09:20:22.000|阅读 1217 次

概述:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

1. 自动装箱与拆箱 对应C#

      例1.1
    Integer i = 10;
  int j = i;

2. 更优化的for循环 对应就C#---foreach循环

  例2.1
    String[] names = {"BadBoy","GoodBoy","HappyGirl","sadGirl"};
  for(String option: names)
     {
         System.out.println(option);
  }
  
      例2.2 加泛型 对应C++模板
    import java.util.*;
  ArrayList animals = new ArrayList();
  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;
  }
  */
  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();


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:赛迪网

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP