Java "Variable Expected" error on list.get(0) = 2

Viewed 753

Here is a simple java code that I wrote:

    List<Integer> list = new ArrayList<>();
    list.add(0);
    list.get(0) = 2; // Trying to set first list element's value to 2

The third line gives me an error, it says:

java: unexpected type
required: variable
found:    value

Does anyone know why I am getting this type of error?

6 Answers

set() method is used to set the element in the particular index

List<Integer> list = new ArrayList<>();
list.add(0);
list.set(0, 2);

Try this to add in beginning

list.add(0, 2);

get(int index) is a getter and it will return Integer from your list but it doesn't allow you to set it's value. To set value at given index, use set(int index, Integer element).

Keep in mind that using set(int index, Integer element) is for updating your list - so in your case list.get(0) cannot return null. If this object doesn't exist, use add(Integer element) as you did before :)

If "Trying to set first list element's value to 2" is what you are trying to do:

List<Integer> list = new ArrayList<>();
list.add(2); // add '2' at the first available position, ie 0th index
System.out.println(list.get(0)); // get the value from 0th index

In Java method calls (like list.get(_)) cannot be lvalues (left-hands of the = operator). Therefore, it is illegal to assign values to method calls, even if they are getters. Indeed, a getter may return and compute anything, even be a constant function always returning 42. What variable should receive the right-hand value then?

As other answers suggest, please consider using list.set(_, _) method.

The problem is in expression

list.get(0) = 2;

Methd List#get(int index) returns the element at the specified position in the List. So left side of expression is a value not a variable. You can't set value to another value.

Use List#add method to append element to the end of List:

  list.add(2);

or to add element to specified position 0:

  list.add(0,2);

If you need to replace element at particular index use List#set method:

  list.set(0,2);
Related