嗨,我想創建一個接受 Object 串列的方法,如下所示:
public static String formatList(List<Object> listToFormat,int indentationSize){
String indentation = Stream.generate(()->"\t").limit(indentationSize).collect(Collectors.joining());
String newIndentedLine = "\n" indentation;
return newIndentedLine listToFormat.stream()
.map(Object::toString)
.collect(Collectors.joining(newIndentedLine));
}
但是當我嘗試做這樣的事情時:
List<Car> cars = new ArrayList<>();
...
Formater.formatList(cars);
不允許。
uj5u.com熱心網友回復:
Java 不允許這樣做,因為 aList<Car>不是 aList<Object>即使 aCar是Object.
不需要宣告型別引數,因為我們不關心實際的型別是什么。每個參考型別Object都有一個toString方法,所以我們可以替換List<Object>為List<?>:
public static String formatList(List<?> listToFormat, int indentationSize) {
uj5u.com熱心網友回復:
你用來public static <T> String formatList(List<T> listToFormat,int indentationSize){代替接受物件。
代碼:
public static <T> String formatList(List<T> listToFormat,int indentationSize){
String indentation = Stream.generate(()->"\t").limit(indentationSize).collect(Collectors.joining());
String newIndentedLine = "\n" indentation;
return newIndentedLine listToFormat.stream()
.map(Object::toString)
.collect(Collectors.joining(newIndentedLine));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405252.html
標籤:
上一篇:泛型:如何從陣列中填充地圖?
