流操作返回对象而不是列表

时间:2018-10-12 03:22:36

标签: java-8 java-stream

我有以下要执行的代码:

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld{

 public static void main(String []args){
    HelloWorld.TreeNode rootNode = new HelloWorld().new TreeNode<Integer>(4);
    List<Integer> traversal = rootNode.inorderTraversal();
    // Prints 4
    System.out.println(
        String.join(",",
            traversal
                .stream()
                .map(Object::toString)
                .collect(Collectors.toList())
        )
    );
 }

 class TreeNode<K extends Comparable<K>> {

     TreeNode<K> left;
     TreeNode<K> right;
     K val;

     TreeNode(K val, TreeNode<K> left, TreeNode<K> right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }

     TreeNode(K val) {
         this(val, null, null);
     }

     List<K> inorderTraversal() {
         List<K> list = new ArrayList<>();
         list.add(this.val);
         return list;
     }

 }
}

但是,如果我将注释行替换为

System.out.println(
    String.join(",",
        rootNode.inorderTraversal()
            .stream()
            .map(Object::toString)
            .collect(Collectors.toList())
    )
);

我收到以下错误:

HelloWorld.java:14: error: no suitable method found for join(String,Object)
        String.join(",",
              ^
method String.join(CharSequence,CharSequence...) is not applicable
  (varargs mismatch; Object cannot be converted to CharSequence)
method String.join(CharSequence,Iterable<? extends CharSequence>) is not 
applicable
  (argument mismatch; Object cannot be converted to Iterable<? extends 
CharSequence>)
Note: HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

我看到了一个非常相似的问题(Why does this java 8 stream operation evaluate to Object instead of List<Object> or just List?),但是我看不出我的解决方案如何规避用户遇到的问题,因为rootNode.inorderTraversal()返回了List<Integer>而不是List

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

这是因为您正在使用原始类型。使用通用类型对它进行参数化。

HelloWorld.TreeNode<Integer> rootNode = new HelloWorld().new TreeNode<>(4);

这将解决此问题。如果您没有在左侧提供通用类型参数,则将List声明为原始类型。