練習(xí)一:函數(shù)式接口
1.定義一個(gè)函數(shù)式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解 FunctionalInterface
2.在測(cè)試類中定義static void showLongTime(CurrentTimePrinter timePrinter),該方法的預(yù)期行為是使用timePrinter打印系統(tǒng)當(dāng)前毫秒值
3.測(cè)試showLongTime(),通過(guò)lambda表達(dá)式完成需求
答案
TimePrinter接口:
FunctionalInterfacepublic interface CurrentTimePrinter{void printCurrenTime();}
測(cè)試類:
public class Test01{public static void main(String[]args){showLongTime(()->System.out.println(System.currentTimeMillis()));}public static void showLongTime(CurrentTimePrinter timePrinter){timePrinter.printCurrentTime();}}
練習(xí)二:函數(shù)式接口
1.定義一個(gè)函數(shù)式接口IntCalc,其中抽象方法int calc(int a,int b),使用注解 FunctionalInterface
2.在測(cè)試類中定義static void getProduct(int a,int b,IntCalc calc),該方法的預(yù)期行為是使用calc得到a和b的乘積并打印結(jié)果
3.測(cè)試getProduct(),通過(guò)lambda表達(dá)式完成需求
答案
IntCalc接口:
FunctionalInterfacepublic interface IntCalc{int calc(int a,int b);}
測(cè)試類:
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);}}
練習(xí)三:靜態(tài)方法引用
1.定義一個(gè)函數(shù)式接口NumberToString,其中抽象方法String convert(int num),使用注解 FunctionalInterface
2.在測(cè)試類中定義static void decToHex(int num,NumberToString nts),該方法的預(yù)期行為是使用nts將一個(gè)十進(jìn)制整數(shù)轉(zhuǎn)換成十六進(jìn)制表示的字符串,tips:已知該行為與Integer類中的toHexString方法一致
3.測(cè)試decToHex(),使用方法引用完成需求
答案
NumberToString接口:
FunctionalInterfacepublic interface NumberToString{String convert(int num);}
測(cè)試類:
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);}}
以上就是長(zhǎng)沙達(dá)內(nèi)教育java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“技術(shù)分享,Java函數(shù)練習(xí)題及答案”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。