【问题标题】:Return Tuple from Java Method从 Java 方法返回元组
【发布时间】:2013-05-27 20:35:14
【问题描述】:

我写了一个java类:

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
}

但是当我创建这样的函数时:

public Tuple<boolean, String> getResult()
{
    try {
        if(something.equals(something2))
             return new Tuple(true, null);
    }
    catch (Exception e){
        return new Tuple(false, e.getMessage());
}

但是,我收到以下编译错误:

unexpected type
  required: reference
  found:    boolean

我能做什么?

【问题讨论】:

  • "required:reference; found: boolean" 这告诉你它找到了类型boolean,它期待一个“引用”类型,即某种对象.

标签: java tuples


【解决方案1】:

泛型不适用于原始类型。使用Boolean 而不是boolean

public Tuple<Boolean, String> getResult() {
    //your code goes here...
}

【讨论】:

    【解决方案2】:

    这就是引入 Boolen、Integer、Long 等类的原因。在 java 中有几个 api 需要一个对象而不是原始类型。

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2013-02-12
      • 2014-11-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多