更新時(shí)間:2020-06-11 11:25:03 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2336次
練習(xí)一:函數(shù)式接口
1.定義一個(gè)函數(shù)式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解 FunctionalInterface
2.在測試類中定義static void showLongTime(CurrentTimePrinter timePrinter),該方法的預(yù)期行為是使用timePrinter打印系統(tǒng)當(dāng)前毫秒值
3.測試showLongTime(),通過lambda表達(dá)式完成需求
答案
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();
}
}
練習(xí)二:函數(shù)式接口
1.定義一個(gè)函數(shù)式接口IntCalc,其中抽象方法int calc(int a,int b),使用注解 FunctionalInterface
2.在測試類中定義static void getProduct(int a,int b,IntCalc calc),該方法的預(yù)期行為是使用calc得到a和b的乘積并打印結(jié)果
3.測試getProduct(),通過lambda表達(dá)式完成需求
答案
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);
}
}
練習(xí)三:靜態(tài)方法引用
1.定義一個(gè)函數(shù)式接口NumberToString,其中抽象方法String convert(int num),使用注解 FunctionalInterface
2.在測試類中定義static void decToHex(int num,NumberToString nts),該方法的預(yù)期行為是使用nts將一個(gè)十進(jìn)制整數(shù)轉(zhuǎn)換成十六進(jìn)制表示的字符串,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);
}
}
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對“技術(shù)分享,Java函數(shù)練習(xí)題及答案”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743