Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查自定义类列表中是否存在变量_Java_Android - Fatal编程技术网

Java 检查自定义类列表中是否存在变量

Java 检查自定义类列表中是否存在变量,java,android,Java,Android,我有一个我创建的自定义类对象的列表 itemName是一个具有普通字符串名称的变量 。这不起作用。您的代码不起作用,因为您正在检查itemName和项目本身 按如下方式操作: boolean found=false; for(Grocery g: GroceryActivity.list){ if(g.getItemName().equals(itemName)){ found=true; break; } } if(!found){ /

我有一个我创建的自定义类对象的列表


itemName是一个具有普通字符串名称的变量
。这不起作用。

您的代码不起作用,因为您正在检查
itemName
和项目本身

按如下方式操作:

boolean found=false;
for(Grocery g: GroceryActivity.list){
    if(g.getItemName().equals(itemName)){
        found=true;
        break;
    }
}
if(!found){
    //...do whatever you want to do
}

其中,
itemName
是要签出的项目的名称,
getItemName
类杂货店中
itemName
的获取者,
杂货店
签出
是完全不同的对象,您无法使用
等于
包含
。如果
CheckOut
类包含的项目比
杂货店
对象多,那么我建议将
杂货店
对象本身添加为
CheckOut
对象的属性,以便使用比较方法

因此,
CheckOut
类可能如下所示

public class CheckOut {
    public long checkOutTime; 
    // ... other extra attributes can go here

    // Add the Grocery object as an attribute
    public Grocery groceryItem; 
}
现在,在创建
结帐
对象时,您基本上是在其中创建一个杂货项目,现在您可以与
杂货活动
中的项目列表进行比较

boolean itemAdded = false;
for (CheckOut checkout : GroceryActivity.list) {
    if (checkout.groceryItem.getName().equals(itemName) {
        // Already added to the checkout
        itemAdded = true;
        break;
    }
}

if (!itemAdded) {
    GroceryActivity.list.add(hisCheckOut);
    GroceryActivity.totalItemsPrice += itemTotalPrice;
}
我希望这有帮助

public class CheckOut {
    public long checkOutTime; 
    // ... other extra attributes can go here

    // Add the Grocery object as an attribute
    public Grocery groceryItem; 
}
boolean itemAdded = false;
for (CheckOut checkout : GroceryActivity.list) {
    if (checkout.groceryItem.getName().equals(itemName) {
        // Already added to the checkout
        itemAdded = true;
        break;
    }
}

if (!itemAdded) {
    GroceryActivity.list.add(hisCheckOut);
    GroceryActivity.totalItemsPrice += itemTotalPrice;
}