Floose
Floose

Reputation: 535

remove() in Arraylists of Arraylists not working

I'm declaring the following two classes:

   public class formula
    {
    ArrayList<values> var= new ArrayList<values>;
}

public class values
{
    int val;
    void addval(int val1)
    {
        val=val1;
    }
}

I am declaring an ArrayList of type formula.

 ArrayList<formula> S= new ArrayList<formula>;

When I try to execute the following statement:

  S.get(i).var.remove(b);

where i is a loop variable

I don't get any error and it compiles fine, but doesn't delete the instance of var(b) for formula(i). The value still remains. What is wrong? I am not using Iterators at all, just a loop to traverse through all the instances of formula().

b is an integer. Essentially the index of the element in the var arraylist I'm trying to delete.

Upvotes: 0

Views: 228

Answers (2)

Jeewantha
Jeewantha

Reputation: 985

If b = the key, it better be a values object. Here the object b should have the the same hashCode as the key and the equals() method should return true. In Java for two objects obj1 and obj2 to be be considered as the same, the following conditions should be satisfied.

  1. obj1.hashCode()== obj2.hashCode()
  2. obj1.equals(obj2)== true

Upvotes: 2

Vishal
Vishal

Reputation: 3279

You must override equals and hashcode while using collection API's. Otherwise you will see lot of unpredictable results in your code...

If you are new to Java, make it a habit to override equals, hashcode and toString methods.

Upvotes: 2

Related Questions