【问题标题】:How to correctly create method accepting list of objects如何正确创建方法接受对象列表
【发布时间】:2022-01-06 17:09:34
【问题描述】:

您好,我想创建一个接受对象列表的方法,如下所示:

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);

这是不允许的。

【问题讨论】:

  • 您可以尝试public static &lt;T&gt; String formatList(List&lt;T&gt; listToFormat,int indentationSize){ 来接受对象吗?
  • 它正在工作!!!谢谢!您能否将其添加为答案,以便我接受并关闭此问题。

标签: java list generics


【解决方案1】:

Java 不允许这样做,因为 List&lt;Car&gt; 不是 List&lt;Object&gt;,即使 CarObject

没有必要声明类型参数,因为我们并不关心实际的类型是什么。每个引用类型都源自Object,它有一个toString 方法,所以我们可以将List&lt;Object&gt; 替换为List&lt;?&gt;

public static String formatList(List<?> listToFormat, int indentationSize) {

【讨论】:

  • 您的回答与@Alias 的回答有什么区别?两者都有效...
  • 是的,两个答案都有效,但我提供了一个(稍微)不太复杂的解决方案。
【解决方案2】:

您使用public static &lt;T&gt; String formatList(List&lt;T&gt; 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));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2017-04-18
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多