无法向< Long>添加整数数组列表 [英] Cannot add an integer to <Long> ArrayList

查看:99
本文介绍了无法向< 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)

现在它的工作原理如下:

Now it worked putting it like this :

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

但是为什么它没有隐含地自我投射?

But why didn't it implicitly cast itself ?

推荐答案

当您尝试以下代码时:

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

您正在尝试将原始整数值添加到 Long的集合对象。这不起作用,也不会装箱这些值,这将产生整数。这也失败了,因为 Integer 无法存储在 Long 的集合中。但是,以下代码可以使用:

you are trying to add primitive integer values to a collection of Long objects. This doesn't work, and neither does boxing these values, which would yield an Integer. This also fails, because an Integer cannot be stored inside a collection of Long. However, the following code would work:

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

这里我们传递原始的 long 值,然后可以装箱到

Here we are passing primitive long values, which can then be boxed to Long.

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

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