简体   繁体   English

Java-是否未设置对象?

[英]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[] . 考虑下面的代码,尝试将Product对象添加到productList ,它是类型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 . 就像注释一样,打印结果为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. 更新:我已经在!= null子句中运行了debug-printouts,对象和子句的其余部分都正常运行。

In your for-each-loop the variable p is a temporary variable to which the contents of productList will be assigned. 在for-each-loop中,变量p是一个临时变量, productList的内容将分配给该临时变量。 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) 如果没有break ,则将product分配给所有null项目(实际上最好使用boolean s来处理循环中断,但这也可行)

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. 您不能使用for-each循环(也称为“增强型” for循环)来设置数组变量,因为它在循环内部使用了temp变量。 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. 您可以使用它来更改数组已保存的对象的状态,因为temp变量将引用同一对象,但不能设置引用本身。 Solution: use a standard for loop. 解决方案:使用标准的for循环。

From the Java Language Specification, §14.14.2 : 根据Java语言规范§14.14.2

The enhanced for statement is equivalent to a basic for statement of the form: 增强的for语句等效于以下形式的基本for语句:

 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. productList[0] ,为什么从未设置productList[0] p is set, for the duration of that loop iteration, but never productList[0] . 在该循环迭代的持续时间内设置了p ,但未设置productList[0]

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

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