Java Integer不能被强制加倍.构造函数调用强制执行

Chr*_*yer 2 java

我花了一些时间调试我的代码.

我发现的是相当奇怪的,我希望有人可以向我解释发生了什么.

首先,这给出了编译时错误:

double x = 5.0;
int y = x;
Run Code Online (Sandbox Code Playgroud)

是的,因为你必须明确地将它转换成双重使用(double).

我有一个带有以下构造函数的对象:

public class MovesValue {
    private ArrayList<Integer> moves;
    private Double value;

    public MovesValue(Integer move, double value) {
        this.moves = new ArrayList<Integer>();
        moves.add(move);
        this.value = value;
    }

    public MovesValue(ArrayList<Integer> moves, double value) {
        this.moves = moves;
        this.value = value;
    }

    public MovesValue() {
    }

    public MovesValue(double value) {
        this.value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我正在调用这样的构造函数:

       int moveToMake = beginMoves;            
       MovesValue rv = new MovesValue(moveToMake);
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,Java调用了以double为参数的构造函数.

它不应该抱怨找不到合适的构造函数吗?

编辑

我已经创建了现在也使用Integer的构造函数.然而,令我惊讶的是,Java仍然会调用带有double的构造函数.它是否需要使用Integer而不是int

好的,我觉得很傻.MovesValue由于某种原因,IntelliJ没有编译我的.重新启动后,它完美地工作.所以我很抱歉这些家伙!

das*_*ght 6

Java没有问题转换intdouble隐式 - 如果没有强制转换,以下内容完全有效:

int x = 5;
double y = x;
Run Code Online (Sandbox Code Playgroud)

你对MovesValue构造函数的调用是成功的,因为这是Java传递int给构造函数时调用的相同类型的转换double.

尝试将一个double构造函数传递给构造函数int会在编译时导致问题:

public MovesValue(int value) {              // <<== Changed the type of value
    this.value = value;
}
...
double moveToMake = beginMoves;            
MovesValue rv = new MovesValue(moveToMake); // <<== This does not compile
Run Code Online (Sandbox Code Playgroud)