0

I need help with removing just added element from the arrayList.

I have a private static ArrayList<Position> positions = new ArrayList<>() to which I'm adding objects of the class Position with parameters name, quantity, and price.

Than I have a method adding objects to the list, and in case if the same product is added for the second time, it is supposed to add the quantity to the first object of that name and remove that second one.

So far I have this method:

public void addPosition(Position p) {

    for (Position poz: positions) {
        if (poz.getname().equals(p.getname())) {
            poz.setquantity(poz.getquantity() + p.getquantity());
        }
    } positions.add(p);

}

Adding quantities works just fine, but I've got problem with removing the element with recurring name.

Please help.

2
  • 2
    Might it be worth using a Map<String, Position> instead of an ArrayList<Position>? Commented Jun 16, 2017 at 20:32
  • I'm relatively new to programing and this was the way i thought of so far. I will learn about maps and try to do it that way as well. Thanks! Commented Jun 16, 2017 at 20:37

2 Answers 2

2

You shouldn't add duplicate items and then remove them. Just declare a method which handles adding items correctly; that is, it adds the item if it does not exist, and it updates the quantity if it does exist.

It should look like this:

public void addPosition(Position addition) {

  //flag to track whether the new item exists in the list
  boolean itemExists = false;

  //go through the list looking for an item with the passed name to update
  for (Position existing : positions) {
    if (existing.getName().equals(addition.getName())) {
      existing.setQuantity(existing.getQuantity() + addition.getQuantity());
      itemExists = true;
    }
  }

  //if no matching item was found, add the new item
  if (!itemExists) {
    positions.add(addition);
  }
}

The above should work. If you care about performance, it might be better to use a HashMap so you can look up the Position by name instead of looping through the whole list each time.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are interested to know other data Structure , i want suggest you HashSet , by default it will not insert duplicates for primitive objects . In your case the only thing you need to do to your Position class , is to add equals and hashCode methods . As getters and setters Eclipse for example will create by him self .

hashCode()

As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode(); It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.

equals()

This particular method is used to make equal comparison between two objects. There are two types of comparisons in Java. One is using “= =” operator and another is “equals()”. I hope that you know the difference between this two. More specifically the “.equals()” refers to equivalence relations. So in broad sense you say that two objects are equivalent they satisfy the “equals()” condition. If you look into the source code of Object class you will find the following code for the equals() method.

Here a complete working example ( you can modify your class following this cose)

import java.util.HashSet;

public class Zhashset{

    private int num;

    public Zhashset(){

    }


    public int getNum() {
        return num;
    }


    public void setNum(int num) {
        this.num = num;
    }


    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + num;
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Zhashset other = (Zhashset) obj;
        if (num != other.num)
            return false;
        return true;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashSet<Zhashset> hs = new HashSet<Zhashset>();
        hs.add(new Zhashset());
        hs.add(new Zhashset());

        for(Zhashset item : hs)
        System.out.println(item.getNum());
    }
}

Output will be : 0 written only once.

2 Comments

but this doesn't handle his issue, which is that when an item is already in the data its quantity should be modified.
Yes man , you are right , my purpose was only to show another data structure , not the solution beacuse you already wrote the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.