The left-hand side of an assignment must be a variable

前端 未结 6 1787
天涯浪人
天涯浪人 2020-12-12 02:06

Why doesn\'t this work?

private List xShot = new ArrayList();
     ...codes
     ...codes
     ...codes
     ...codes
     xSho         


        
相关标签:
6条回答
  • 2020-12-12 02:11

    Although xShot.get(0) is a number, it is not a variable. You need to provide a variable for this to work. That said

    int i = xShot.get(0);
    i += 5;
    

    Will not work. i will be incremented by 5, but xShot's object in location 5 is not the same object. You need to get, modify, and set the variable.

    For example:

    xShot.set(0, xShot.get(0) + 5);
    
    0 讨论(0)
  • 2020-12-12 02:17

    xShot.get(0) is a method call that returns a value. A variable is something you declare with a type that holds a value, like int x;, String name;, or List<Integer> xShot from your example. Those are the only things in Java that you can assign a value to using an assignment operator.

    0 讨论(0)
  • 2020-12-12 02:19

    It is like saying in Java:

    5 = 6; // "Assign 5 to 6"
    

    The left side (5) isn't variable.

    Why is this example statement relevant? Because of Java uses always "pass by value". Which means that the return value of a method is also "return by value". This is pure mathematical: you can't change a value, you can change a variable. The same for Java. Five can never become six.
    In other words: Only a value can be assigned to a variable.

    So, the correct way of doing what you want is:

    xShot.set(0, xShot.get(0) + 5);
    

    Edit: In your situation: xShot.get(int) doesn't return a variable, but a value.

    0 讨论(0)
  • 2020-12-12 02:23

    The left-hand side of the assignment has to be explicitly a variable because in your case of statement , the expression could be a constant also , which would be a error if allowed

    0 讨论(0)
  • 2020-12-12 02:30

    xShot.get(0) returns an object; it isn't a variable, so you can't assign to it.

    Also, Integer is immutable (you can't change its value), so you would have to replace the object at position 0 with a new Integer that has the calculated value.

    You can achieve the intention of that line like this:

    xShot.set(0, xShot.get(0) + 5);
    
    0 讨论(0)
  • 2020-12-12 02:32

    If you just want to increment by 5 and aren't limited to List<Integer> specifically, you could avoid arguably verbose xShot.set(0, xShot.get(0) + 5) and do this instead:

    List<AtomicInteger> xShot = new ArrayList<AtomicInteger>();
    xShot.get(0).addAndGet(5);
    

    This will increment the value of the AtomicInteger in xShot.get(0) by 5 in-place without further ado.

    0 讨论(0)
提交回复
热议问题