不能将整数添加到 <Long>数组列表 [英] Cannot add an integer to <Long> ArrayList

查看:28
本文介绍了不能将整数添加到 <Long>数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个ArrayList:

I have created an ArrayList:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
class Main{
    static ArrayList<Long> fibo_list=new ArrayList<Long>();
    static int current_index;
    public static void main(String args[]){
        fibo_list.add(0);
        fibo_list.add(1);
        fibo_list.add(1);

三个 fibo_list.add() 抛出相同类型的错误.这是第一个:

The three fibo_list.add() throws the same type of error. Here's the first one:

error: no suitable method found for add(int)
    fibo_list.add(0);
             ^
method ArrayList.add(int,Long) is not applicable
  (actual and formal argument lists differ in length)
method ArrayList.add(Long) is not applicable
  (actual argument int cannot be converted to Long by method invocation conversion)
method AbstractList.add(int,Long) is not applicable
  (actual and formal argument lists differ in length)
method AbstractList.add(Long) is not applicable
  (actual argument int cannot be converted to Long by method invocation conversion)
method AbstractCollection.add(Long) is not applicable
  (actual argument int cannot be converted to Long by method invocation conversion)

现在它像这样工作:

fibo_list.add((long)0);
fibo_list.add((long)1);
fibo_list.add((long)1);

但它为什么不隐式地强制转换自己?

But why didn't it implicitly cast itself ?

推荐答案

您在转换和拳击之间感到困惑.

You are getting confused between casting and boxing.

当 int 转换为 Integer 时 - 这称为装箱,而反向过程称为拆箱.

When int gets converted to Integer - it's called boxing and revrese process is called unboxing.

JAVA 支持自动装箱,这意味着您的原语将在需要时自动转换为它的包装类 &反之亦然.例如 int -> Integer, long -> Long 等

JAVA supports autoboxing, which means your primitive will eb automatically converted to it's wrapper class when required & vice versa. E.g int -> Integer, long -> Long etc.

Java 还支持基元之间的转换,这意味着 int 基元可以隐式转换为 long 基元.

Java also supports casting among primitives which means int primitive can be implicitly casted to long primitive.

您要实现的是上述操作的组合.您想将 int 转换为 Long,这需要 2 个步骤,这可以通过 2 种不同的方式实现(让我们假设以下是可能的):

What you are trying to achieve is a combination of above to operations. You want to convert int to Long which will require 2 steps, which may be achieved in 2 different ways(let's assume for a moment following are possible):

方式一:

  1. 将 int 转换为 long
  2. 拳龙到龙

方式 2:

  1. 将整数装箱为整数
  2. 将整数转换为长整数

由于没有明确选择哪种方式,因此 JAVA 不允许任何 2 步过程作为自动转换.

Since there is no clarity which way to choose, therefore JAVA does not allow allow any of the 2 step process as an automatic conversion.

这篇关于不能将整数添加到 &lt;Long&gt;数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆