java 意外类型所需变量找到值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14834224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:33:22  来源:igfitidea点击:

Unexpected type required variable found value

javaarraylist

提问by user1633277

public class example
{
    public ArrayList<Integer> ToFill = new ArrayList<>();

    public void Alter(int Value , int Position)
    { 
      ToFill.get(Position) = Value ;  // this line has an error 
    }
}

For some reason this code gives compilation Error ,could anyone explain why?

出于某种原因,这段代码给出了编译错误,谁能解释一下原因?

回答by Eng.Fouad

ToFill.get(Position)returns a value where the left-hand side of the assignment must be a variable. Instead, use set(index, element)as follows:

ToFill.get(Position)返回一个值,其中赋值的左侧必须是一个变量。相反,使用set(index, element)如下:

ToFill.set(Position, Value);

However, what you are doing is only valid if you are using arrays, for example:

但是,您所做的仅在使用数组时才有效,例如:

Integer[] array = ...
array[Position] = Value;


As a side note, always use Java naming convention:

作为旁注,始终使用 Java 命名约定:

  • toFillinstead of ToFill
  • alterinstead of Alter
  • positioninstead of Position.
  • valueinstead of Value.
  • toFill代替 ToFill
  • alter代替 Alter
  • position而不是Position.
  • value而不是Value.