更新時間:2020-06-11 11:25:03 來源:動力節點 瀏覽2354次
練習一:函數式接口
1.定義一個函數式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解 FunctionalInterface
2.在測試類中定義static void showLongTime(CurrentTimePrinter timePrinter),該方法的預期行為是使用timePrinter打印系統當前毫秒值
3.測試showLongTime(),通過lambda表達式完成需求
答案
TimePrinter接口:
FunctionalInterface
public interface CurrentTimePrinter
{
void printCurrenTime();
}
測試類:
public class Test01{
public static void main(String[]args){
showLongTime(()->System.out.println(System.currentTimeMillis()));
}
public static void showLongTime(CurrentTimePrinter timePrinter){
timePrinter.printCurrentTime();
}
}
練習二:函數式接口
1.定義一個函數式接口IntCalc,其中抽象方法int calc(int a,int b),使用注解 FunctionalInterface
2.在測試類中定義static void getProduct(int a,int b,IntCalc calc),該方法的預期行為是使用calc得到a和b的乘積并打印結果
3.測試getProduct(),通過lambda表達式完成需求
答案
IntCalc接口:
FunctionalInterface
public interface IntCalc{
int calc(int a,int b);
}
測試類:
public class Test02{
public static void main(String[]args){
getProduct(2,3,(a,b)->a*b);
}
public static void getProduct(int a,int b,IntCalc intCalc){
int product=intCalc.calc(a,b);
System.out.println(product);
}
}
練習三:靜態方法引用
1.定義一個函數式接口NumberToString,其中抽象方法String convert(int num),使用注解 FunctionalInterface
2.在測試類中定義static void decToHex(int num,NumberToString nts),該方法的預期行為是使用nts將一個十進制整數轉換成十六進制表示的字符串,tips:已知該行為與Integer類中的toHexString方法一致
3.測試decToHex(),使用方法引用完成需求
答案
NumberToString接口:
FunctionalInterface
public interface NumberToString{
String convert(int num);
}
測試類:
public class Test03{
public static void main(String[]args){
decToHex(999,Integer::toHexString);
}
public static void decToHex(int num,NumberToString nts){
String convert=nts.convert(num);
System.out.println(convert);
}
}
以上就是動力節點java培訓機構的小編針對“技術分享,Java函數練習題及答案”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習