目录
这是我从网上看到的题目,自己看题目,自己写代码,只注重了功能,但是没有主动效率之类的。这次的三个题目比较简单,主要是函数式接口很抽象,如果代码短一些还好,如果长的,简直就是天书啊,根本跟平时人类的思考方式一点都不一样。
题目1
-
第一题
- 定义一个函数式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解@FunctionalInterface
- 在测试类中定义static void showLongTime(CurrentTimePrinter timePrinter),该方法的预期行为是使用timePrinter打印系统当前毫秒值
- 测试showLongTime(),通过lambda表达式完成需求
代码如下:
@FunctionalInterface
public interface CurrentTimePrinter {
void printCurrentTime();
}
public class Test01 {
public static void showLongTime(CurrentTimePrinter timePrinter){
timePrinter.printCurrentTime();
}
public static void main(String[] args) {
showLongTime(()-> System.out.println(System.currentTimeMillis()));
}
}
题目2
-
第二题
- 定义一个函数式接口IntCalc,其中抽象方法int calc(int a , int b),使用注解@FunctionalInterface
- 在测试类中定义static void getProduct(int a , int b ,IntCalc calc), 该方法的预期行为是使用calc得到a和b的乘积并打印结果
- 测试getProduct(),通过lambda表达式完成需求
代码如下:
@FunctionalInterface
public interface IntCalc {
int calc(int a,int b);
}
public class Demo2 {
public static void getProduct(int a,int b,IntCalc calc){
int result = calc.calc(a,b);
System.out.println(result);
}
public static void main(String[] args) {
getProduct(1,5,(a,b)-> {return a*b;});
}
}
题目3
-
第三题
- 定义一个函数式接口NumberToString,其中抽象方法String convert(int num),使用注解@FunctionalInterface
- 在测试类中定义static void decToHex(int num ,NumberToString nts), 该方法的预期行为是使用nts将一个十进制整数转换成十六进制表示的字符串,tips:已知该行为与Integer类中的toHexString方法一致
- 测试decToHex (),使用方法引用完成需求
代码如下:
@FunctionalInterface
public interface NumberToString {
String convert(int num);
}
public class Demo3 {
public static void decToHex(int num,NumberToString nts){
String s = nts.convert(num);
System.out.println(s);
}
public static void main(String[] args) {
decToHex(11,num -> { return Integer.toHexString(num);});
decToHex(12,Integer::toHexString);
}
}