0

I have a method which add element to an arraylist My task is to Modify the addProduct method so that a new product cannot be added to the product list with the same ID as an existing one.

Since both number and string are in the same word "item" and stored on the same index, I don't know how I can just get the number. I need the number to test to see if the number already exist

Any suggestion on how I should do this?

The way I add to the arraylist is like this below:

(new Product(132, "Clock Radio"))

public void addProduct(Product item)
{
 stock.add(item);
 }
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
radder
  • 21
  • 1
  • 1
  • 1
  • Ummm ... that code is not valid java. Try again. – Stephen C Jul 18 '11 at 09:16
  • @radder, are u open to change the type of 'stock' to Set ?. This will solve your problem. – Santosh Jul 18 '11 at 09:25
  • Do you mean you have an object of type Product, which contains some members and you don't know how to access a specific member? – Tadeusz Kopec for Ukraine Jul 18 '11 at 09:58
  • @Tadusz Kopec I have an arraylist that contain name on product and product id number.Both id and name are in the same word "item" Public void addProduct(Product item) and I don't know how I can get only the number out from the item soI can use that number to see if the number already exist in the arraylist. Any suggestion? – radder Jul 18 '11 at 14:11
  • @Stephen Why is this not a valid java code? the code line with "(new Product(132, "Clock Radio"))" is only there to show how I add the product name and id into the parameter. You did not tell how I can get the number out of the word "item" which I asked you pro programmer to help me with – radder Jul 18 '11 at 14:16
  • It was incorrect before someone edited it. Check the edit. – Stephen C Jul 18 '11 at 22:34

5 Answers5

4

I would greatly recommend you to go for Set inside the addProduct() method.

From the Javadocs,

SET
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

Implement like this,

public static boolean checkDuplicate(ArrayList list) {
 HashSet set = new HashSet();
 for (int i = 0; i < list.size(); i++) {
  boolean val = set.add(list.get(i));
  if (val == false) {
    return val;
  }
 }
 return true;
}
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
  • Does not address the question: "Since both number and string are in the same word "item" and stored on the same index, I don't know how I can just get the number." Also requires you to implement "equals" and "hashCode" in a way that may not be appropriate elsewhere. And you lose insertion order. – Thilo Jul 18 '11 at 09:20
  • Iterating every time while adding an item might be a costly affair as the collection grows. – Santosh Jul 18 '11 at 09:23
  • Also creating a new HashSet object everytime you check for a duplicate before adding is unnecessary if you can create it once and then manipulate or traverse when adding an item. – rtheunissen Jul 18 '11 at 10:17
  • @Thilo Have you any idea on how I can get the number from the word "item" when the word contain both number and string? – radder Jul 18 '11 at 14:24
1
public void addProduct(Product item){
   for (Product p: stock)
      if (p.getId() == item.getId())
         return;
   stock.add(item);
}
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • I try to use a second arraylist to add the product item to and then loop through it to get the number, but I have the same problem again, I'm not able to get just the number. – radder Jul 18 '11 at 10:36
1

I would use a java.util.Set. You would need to implement the equals() and hashcode() methods of the Product class based on the two fields passed into the constructor.

spot35
  • 888
  • 4
  • 9
  • careful, though, about the potential side-effects of implementing equals and hashCode for just the case at hand. Who knows if products should be considered equal based on just the ID in all situations. – Thilo Jul 18 '11 at 09:22
1

Try using a HashMap with the ID as the Key and the Item as the Value. In an HashMap you cant duplicate Items with the same Key, so your problem is solved at the bottom of your programming. :)

Michele
  • 6,126
  • 2
  • 41
  • 45
0

Create a ProductList class that has an ArrayList field and a integer set to keep track of ID's that have been added. When you add an item, check if the set already contains the item's ID. If it doesn't, add the item to the ArrayList. So this basically wraps around an ArrayList quite nicely. Here's how I would do it:

public class ProductList{
...
    private ArrayList<Product> list = new ArrayList<Product>();
    private Set<Integer> ids = new Set<Integer>();
...
    public void addProduct(Product product){
       if(!ids.contains(product.getID())){
            list.add(product);
            ids.add(product.getID());
           }
         }

    public Product removeProduct(Product product){
       if(!list.contains(product)) return null;
       ids.remove(product.getID());
       return list.remove(product);
      }
...
    }

You can then just use

ProductList stock = new ProductList();

and stock.addProduct(Product item); in your other class.

If you think you'll be using your list quite extensively, creating practical constructors to integrate with your data fields will be very useful as well.

This is a very good approach from an abstraction point of view, however it's probably not the most efficient way of doing it.

rtheunissen
  • 7,347
  • 5
  • 34
  • 65
  • Another ArrayList instead of the Set would also work just as well. – rtheunissen Jul 18 '11 at 10:13
  • I have tried using `if(list.contains(product){ }` but it doesn't work. My product will be the same and a product in the list but it always falls into the `else` statement rather than the `if` statement. If anyone has any idea, I'd love to know. I'm having to do a load of for loops instead which seems really sloppy. – alsobubbly May 22 '14 at 13:03
  • @alsobubbly What type of object is `product`? If it's a class that you created, you might want to override the `equals` method that is part of the `Object` class. This allows you to define when a `product` is in fact equal to another. The `contains` method calls the `equals` method on each product in the list I think. Give that a shot and report back if you like. Can read more here: [equals method in java](http://stackoverflow.com/q/15175109/828867) http://www.artima.com/lejava/articles/equality.html – rtheunissen May 22 '14 at 23:00
  • Thank you for your help. In the end I figured out that the product object wouldn't match to the product in the products list because it was being treated as a new product item or something like that. The way I got around it was to do an `em.find(Product.class, product.getID());` for each product that I wanted to check the list for and check from the found product object instead of the one in the original list (if that makes sense). This seemed to work fine. – alsobubbly May 23 '14 at 10:02
  • I'm glad you got it to work but I'm not sure if it's the best practice. If you want, you can paste your code in a pastebin and send me the link so I can suggest a few things? Up to you. – rtheunissen May 23 '14 at 21:59
  • Unfortunately I'm unable to do that due to the sensitive nature of the application. Thank you for your help though, if I get chance to put an example together I'll let you know. – alsobubbly May 27 '14 at 13:01