0

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.

11
  • 1
    Most likely that you did not override hashCode and equals on values. Didn't really post enough code to tell you for sure. Commented Nov 21, 2012 at 5:22
  • how does this works "public class formula()" ? Commented Nov 21, 2012 at 5:23
  • 3
    I guarantee you this does not compile "fine". Commented Nov 21, 2012 at 5:24
  • This seems to be a daily occurrence when I post snippets of code from my program.. @MarkPeters What's wrong? Commented Nov 21, 2012 at 5:27
  • @Floose: What does the compiler tell you is wrong? I would hope that you would have tried to compile the snippet you're posting here. Commented Nov 21, 2012 at 5:28

2 Answers 2

2

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.

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

Comments

2

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

Comments

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.