How to add an item only if no other items exist with the same name in the arraylist?

13,816

Solution 1

You need to check if an item with the same name already exists in your list:

public void insertUniqueItem(Item item) {
    if(!contains(item)) {
        cart.add(item);
    }
}

private boolean contains(Item item) {
    for(Item i : cart) {
        if(i.getName().equals(item.getName())) {
           return true;
        }
    }
    return false;
}

Solution 2

I would probably use a LinkedHashMap<String, Item> instead, where the key is the name of the item. That way:

  • You still get to preserve ordering
  • You can easily and efficiently check whether there's already an entry for a given item name.

You'd have something like:

if (!map.containsKey(item.getName()) {
    map.put(item.getName(), item);
}

This only works if you want all items to be unique in terms of name though. If you sometimes want to allow a duplicate name and sometimes not, you probably do want a list, and then you could have something like:

boolean containsItemName(ArrayList<Item> items, String name) {
    for (Item item : items) {
        if (item.getName().equals(name)) {
            return true;
        }
    }
    return false;
}

If you're using Java 8, you could use a stream-based solution:

boolean containsItemName(ArrayList<Item> items, String name) {
    return items.stream().anyMatch(item -> item.getName().equals(name));
}

Solution 3

You can modify your Item class to have the equals and hashcode methods as follows:

public class Item{

    private String name;


    public boolean equals(Object o){
        if (o instanceOf Item and ((Item)o).getName().compareTo(name) == 0){
            return true;
        }
        return false;
    }

    public int hashCode(){
        return name.hashCode();
    }

}

You can now use the contains method of the arrayList to determine if another item exists with the same name in the arrayList or not.

Share:
13,816
Ricardo Desu Perez
Author by

Ricardo Desu Perez

Updated on June 17, 2022

Comments

  • Ricardo Desu Perez
    Ricardo Desu Perez almost 2 years

    How would I go about only inserting an item if the item does not have the same name as the other items in the arraylist within my insertUniqueItem() method?

        public void insertUniqueItem()
        {
    
        }
    
        public static void main(String[] args)
        {
            ShoppingCart sc = new ShoppingCart();
            Item a = new Item("Kraft Cheese", 4, "\"Best Cheese in Town!\"");
            Item b = new Item("Bottle of Water", 2.50, "\"Refreshing Water!\"");
    
            sc.insertItem(a);
            sc.insertItem(b);
    
            sc.printInvoice();
            sc.insertUniqueItem();
    
            sc.print();
    
            DecimalFormat df = new DecimalFormat("#.00");
    
            System.out.println("Total Price: $" + df.format(sc.getTotal()));
        }
    }
    
  • Jon Skeet
    Jon Skeet about 9 years
    That works if items are naturally equal just by name - but if there can be two items with the same name but different other values, it would be somewhat odd for them to be equal, I suspect.
  • Ricardo Desu Perez
    Ricardo Desu Perez about 9 years
    Thank you for your answer, but I wanted to stick with only using my arraylist. I see how this would work though. Once again, thanks :)
  • Ricardo Desu Perez
    Ricardo Desu Perez about 9 years
    Thank you so much :D I love how I didn't have to add hashs or lists to do so. It works :)
  • Ricardo Desu Perez
    Ricardo Desu Perez about 9 years
    Thank you for your answer, but I wanted to stay with only using an arraylist and not using a hash to complete it.
  • willysama
    willysama about 9 years
    true. this is why equals method has to be override to define the rules of unicity before
  • Jon Skeet
    Jon Skeet about 9 years
    I think you've missed my point - if you're overriding it to be equal just on the basis of name, you may well find that elsewhere you want it to be equal based on other properties.
  • nullPointer
    nullPointer about 9 years
    The hash is needed only so that the arraylist can determine if the item exists in it. It doesn't utilize a hash table