阿里云【名师课堂】Java高级开发6 ~ 8:Java基础新特性
随着JDK的更新,每个新版本都会提供许多新特性。
课时6:可变参数
现在假设有这样一个要求:设计一个方法,用于计算任意个数的整数的相加结果。
- 对于这种开发需求,最初只能通过数组的方式来实现。
package rookie.advanced.demo;
public class TestDemo {
public static void main(String[] args) {
System.out.println("RESULT = " + add(new int[] {1 , 2 , 3}));
System.out.println("RESULT = " + add(new int[] {4 , 5 , 6}));
}
/**
* 实现任意个数的数据的相加处理操作
* @param data 要进行相加操作的数组
* @return 返回多个数据的相加结果
*/
public static int add(int[] data) {
int sum = 0 ;
for (int x = 0 ; x < data.length ; x++) {
sum += data[x] ;
}
return sum ;
}
}
- 缺陷:需要设计的不是一个数组,而是任意多个参数,因此需要用到可变参数的概念。
public [static] [final] 返回值 方法名称 (参数类型 ... 参数名称) {}
package rookie.advanced.demo;
public class TestDemo {
public static void main(String[] args) {
System.out.println("RESULT = " + add()); // 可以为空
System.out.println("RESULT = " + add(new int[] {1 , 2 , 3})); // 可变参数可以接收数组
System.out.println("RESULT = " + add(4 , 5 , 6));
}
/**
* 实现任意个数的数据的相加处理操作
* @param data 要进行相加操作的数组
* @return 返回多个数据的相加结果
*/
public static int add(int ... data) { // 本身还是一个数组
int sum = 0 ;
for (int x = 0 ; x < data.length ; x++) {
sum += data[x] ;
}
return sum ;
}
}
注意:
- 如果要传递多个参数,可变参数写在最后;
- 一个方法只能设计一个可变参数。
课时7:foreach输出
foreach循环可以看作增强型for循环。
在Java里对于常用数据集合:数组、类集本身有自己新的输出支持,但是这种支持建议在学习中不要过多使用。
范例:原始数组通过for循环
package rookie.advanced.demo;
public class TestDemo {
public static void main(String[] args) {
int[] data = new int[] {1 , 2 , 3 , 4 , 5} ; // 原始数组
for (int x = 0 ; x < data.length ; x++) {
System.out.println(data[x]) ;
}
}
}
for (数据类型 临时变量 : 数组) {
// 循环次数为数组长度,而每次循环都顺序取出数组的一个元素给临时变量
}
范例:增强型foreach循环
package rookie.advanced.demo;
public class TestDemo {
public static void main(String[] args) {
int[] data = new int[] {1 , 2 , 3 , 4 , 5} ; // 原始数组
for (int x : data) { // 顺序将数组中每个元素赋值给x
System.out.println(x) ;
}
}
}
这种方法可以避免数组越界的问题,但是这种数组操作只适合于简单的处理模式。
课时8:静态导入
假设:现在定义有一个MyMath类,这个类中提供有static的方法。
package rookie.advanced.util;
public class MyMath {
public static int add(int x , int y) {
return x + y ;
}
public static int sub(int x , int y) {
return x - y ;
}
}
该类中所有方法都属于静态方法,因此按照最初的使用原则,肯定是先导入MyMath类,而后利用MyMath类来调用类中的全部的static方法。
范例:使用MyMath类
package rookie.advanced.demo;
import rookie.advanced.util.MyMath;
public class TestDemo {
public static void main(String[] args) {
System.out.println(MyMath.add(10, 20)) ;
System.out.println(MyMath.sub(30, 20)) ;
}
}
在JDK1.8中,如果类中方法全是static方法,则可以直接将这个类的方法导入进来,这样就好比在主类中定义的方法那样,可以被主方法直接调用。
package rookie.advanced.demo;
import static rookie.advanced.util.MyMath.*; // 静态导入
public class TestDemo {
public static void main(String[] args) {
System.out.println(add(10, 20)) ;
System.out.println(sub(30, 20)) ;
}
}