简体   繁体   中英

Java - Object is not being set?

Consider the following code, attempting to add a Product object into a productList , which is an array of the type Product[] .

public void addItem(Product product) {

    for (Product p : productList) {
        if (p != null){
            p = product;
        }
    }

    System.out.println(productList[0]);  // This yields null.

}

Like commented, the print results in null . Why is the product not being set?

Update: I've ran debug-printouts inside the != null clause, and both the object and the rest of the clause is run properly.

In your for-each-loop the variable p is a temporary variable to which the contents of productList will be assigned. Thus you are always just assigning the temporary variable instead of to the items inside the list.

You probably want this:

for (int i = 0; i < productList.length; i++)
{
    if (productList[i] == null)
    {
        productList[i] = product;
        break;
    }
}

Without the break you would assign product to every item that is null (actually it would be better to use boolean s to handle the loop break but this works, too)

You can't use the for-each loop, also known as the "enhanced" for loop, to set array variables since it uses a temp variable inside of the loop. You can use it to change the state of an object already held by the array since the temp variable will refer to the same object, but not to set the reference itself. Solution: use a standard for loop.

From the Java Language Specification, §14.14.2 :

The enhanced for statement is equivalent to a basic for statement of the form:

 for (I #i = Expression.iterator(); #i.hasNext(); ) { VariableModifiersopt TargetType Identifier = (TargetType) #i.next(); Statement } 

So in your case, loosely:

for (int n; n < productList.length; ++n) {
    Product p = productList[n];
    if (p != null) {
        p = product;
    }
}

From that, you can see why productList[0] is never set. p is set, for the duration of that loop iteration, but never productList[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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