简体   繁体   English

Java ArrayList for循环lcv被认为是一个对象,而不是一个int

[英]Java ArrayList for-loop lcv thought to be an object, not an int

I'm trying to make an array with a sequence of variable length, so I decided to use an ArrayList. 我试图制作一个具有可变长度序列的数组,所以我决定使用ArrayList。

Since I want to find the sum of the sequence of numbers, I tried to use the ArrayList.get(int index) method to get the value of an element in the ArrayList, but NetBeans is complaining at me about incompatible types: Object cannot be converted to int for the following code: 由于我想查找数字序列的总和,因此我尝试使用ArrayList.get(int index)方法获取ArrayList中元素的值,但是NetBeans向我抱怨incompatible types: Object cannot be converted to int将以下代码incompatible types: Object cannot be converted to int

int seqLen = sequence.size(); // number of elements in ArrayList sequence
int seqSum = 0; // sum of all elements in the sequence
for(int i = 0; i <= seqLen; i++) {
   int seqPart = sequence.get(i);
   seqSum+= seqPart;
}

Specifically, the line int seqPart = sequence.get(i); 具体来说,这行int seqPart = sequence.get(i);

I'm not sure why it thinks that i is an object and not an int , and this block of code is crucial for the program to work. 我不确定为什么它认为i是一个object而不是一个int ,而这段代码对程序的工作至关重要。

Basically, what am I doing wrong here, I've gone over the JavaDoc for ArrayList a couple times now, but I still haven't figured out what's wrong. 基本上,我在这里做错了什么,我已经遍历了JavaDoc for ArrayList几次,但是我仍然没有弄清楚出什么问题了。

If you look at the JavaDoc , you'll notice that get returns an E . 如果查看JavaDoc ,您会注意到get返回E If you don't define what that E is, it'll default to Object. 如果您没有定义E是什么,它将默认为Object。 An Object can't be assigned to an int. 无法将对象分配给int。 Define your arraylist like this: 像这样定义您的数组列表:

List<Integer> sequence = new ArrayList<>();

This says, "I'm going to fill this ArrayList with Integers". 这说,“我将用整数填充此ArrayList”。 That way when you call get() it'll return an Integer instead of an Object . 这样,当您调用get()它将返回一个Integer而不是Object

This part is a little more advanced and not super important so don't worry if it goes over your head: The reason you can assign that Integer to an int is because of a concept called Auto unboxing . 该部分稍微高级一些,并且不是非常重要,因此不要担心它是否过时:可以将Integer分配给int的原因是因为有一个称为自动拆箱的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM