从ArrayList中移除仅提供一个属性的对象 [英] Remove an object from an ArrayList given only one attribute

查看:49
本文介绍了从ArrayList中移除仅提供一个属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList of Items,我希望能够通过仅输入一个Item属性(例如其编号(int ItemNumber))从列表中删除一个Item.检查项目数量时,我也想这样做.

I have an ArrayList of Items and I want to be able remove one Item from the list by entering only one Item attribute, for example its number (int ItemNumber). I also wanna do the same when I check Item quantities.

这些是我的 equals()& contains()方法,我是否需要在此处进行任何更改?

These are my equals() & contains() methods, do I need to make any changes here?

public boolean contains(T anEntry) {
    boolean found = false;
    for (int index = 0; !found && (index < numberOfEntries); index++) {
    if (anEntry.equals(list[index])) 
        found = true;
    }//end for
    return found;
} // end contains

public boolean equals(Object object){
    Item item = (Item) object;
    if (itemNo == item.itemNo)
        return true;
    return false;
}

推荐答案

如果更改类 Item equals() compareTo()方法,以便它们仅检查一个对象字段,例如 quantity ,这可能导致应用程序其他部分出现奇怪的行为.例如,两个具有不同 itemNo itemName itemPrice 但具有相同数量的商品可以被认为是相等的.此外,如果不每次都更改 equals()代码,就无法更改比较属性.

If you change the class Item equals() and compareTo() methods, so that they check only one object field, such as a quantity, it could result in strange behavior in other parts of your application. For example, two items with different itemNo, itemName, and itemPrice, but with the same quantities could be considered equal. Besides, you wouldn't be able to change the comparison attribute without changing the equals() code every time.

此外,创建自定义的 contains()方法没有任何意义,因为它属于 ArrayList 类,而不属于 Item .

Also, creating a custom contains() method makes no sense, since it belongs to the ArrayList class, and not to Item.

如果可以使用Java 8 ,一种干净的方法是使用新的 Collection

If you can use Java 8, a clean way to do it is to use the new Collection's removeIf method:

假设您有一个具有 num name 属性的 Item 类:

Suppose you have an Item class with the num and name properties:

class Item {
    final int num;
    final String name;

    Item(int num, String name) {
        this.num = num;
        this.name = name;
    }
}

给出一个名为 items List< Item> 和一个名为 number int 变量,该变量表示您想要删除的项目,只需执行以下操作:

Given a List<Item> called items and an int variable called number, representing the number of the item you want to remove, you could simply do:

items.removeIf(item -> item.num == number);

如果您无法使用Java 8 ,则可以使用自定义比较器,二进制搜索和伪对象来实现.

If you are unable to use Java 8, you can achieve this by using custom comparators, binary search, and dummy objects.

您可以为需要查找的每个属性创建一个自定义比较器. num 的比较器如下所示:

You can create a custom comparator for each attribute you need to look for. The comparator for num would look like this:

class ItemNumComparator implements Comparator<Item> {
    @Override
    public int compare(Item a, Item b) {
        return (a.num < b.num) ? -1 : ((a.num == b.num) ? 0 : 1);
    }
}

然后,您可以使用比较器对列表中所需的元素进行排序和搜索:

Then you can use the comparator to sort and search for the desired elements in your list:

public static void main(String[] args) {
    List<Item> items = new ArrayList<>();
    items.add(new Item(2, "ball"));
    items.add(new Item(5, "cow"));
    items.add(new Item(3, "gum"));

    Comparator<Item> itemNumComparator = new ItemNumComparator();
    Collections.sort(items, itemNumComparator);

    // Pass a dummy object containing only the relevant attribute to be searched
    int index = Collections.binarySearch(items, new Item(5, ""), itemNumComparator);
    Item removedItem = null;
    // binarySearch will return -1 if it does not find the element.
    if (index > -1) {
        // This will remove the element, Item(5, "cow") in this case, from the list
        removedItem = items.remove(index);
    }
    System.out.println(removedItem);
}

例如,要搜索诸如名称之类的另一个字段,您需要创建一个名称比较器,并使用它来对列表进行排序和运行二进制搜索.

To search for another field like name, for example, you would need to create a name comparator and use it to sort and run the binary search on your list.

请注意,此解决方案有一些缺点.除非您完全确定自上次排序以来该列表没有改变,否则您必须必须重新排序,然后再运行 binarySearch()方法.否则,它可能无法找到正确的元素.排序复杂度为 O(nlogn),因此根据列表的大小,多次运行它可能会变得非常昂贵.

Note this solution has some drawbacks though. Unless you are completely sure that the list didn't change since the last sort, you must re-sort it before running the binarySearch() method. Otherwise, it may not be able to find the correct element. Sorting complexity is O(nlogn), so running it multiple times can get quite expensive depending on the size of your list.

这篇关于从ArrayList中移除仅提供一个属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆