0

My contains method works properly for smaller indices but then for big indices such as the test cases 1000, 2000, 2999 it does not work. I do not see why. I checked the output for the print statement in the loop which shows that the numbers I am checking for are present in the object array.

Assume the objects in array and element are int. data is Object []

public boolean contains(E element) {
         boolean flag = false;
         if (this.size() == 0) { return flag;}

         for (int i = 0; i < this.data.length; i++) {
              if (element == this.data[i]) { flag = true; }
              System.out.println(this.data[i]);
         }
         return flag;
}

@Test
public void mustGrowArray()  {
      OurSet<Integer> ints = new ArraySet<Integer>();
      for (int i = 0; i < 3000; i++) {
        ints.add(i);
      }
      assertEquals(3000, ints.size());//passes
      assertTrue(ints.contains(1000));// fails
      assertTrue(ints.contains(2000));// fails
      assertTrue(ints.contains(2999));// fails
}
Tom
  • 16,842
  • 17
  • 45
  • 54
  • 1
    Compare with `equals`, not with `==`. – Eran Jun 26 '19 at 06:17
  • thank you! that worked but why was the error happening? – abhishek sharma Jun 26 '19 at 06:19
  • You can have two objects that are .equals but not equal. Eg. `Integer a = new Integer(1); Integer b = new Integer(1);` a==b is false, but a.equals(b) is true. I'm surprised 1000 isn't cached when it is autoboxed. – matt Jun 26 '19 at 06:21
  • Another suggestion: instead of: flag=true you should return true; or break; just after -> it's faster as you don't need to check all the array – NikNik Jun 26 '19 at 06:29

2 Answers2

1

== is not .equals!

Use .equals instead in this line,

if (element == this.data[i])

to

if (element.equals(this.data[i]))

Hope it helps.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
0

Compare with equals instead of ==

use this `for-loop:

for (int i = 0; i < this.data.length; i++) {
    if (element.equals(this.data[i])) {
       flag = true;
    }
    System.out.println(this.data[i]);
}

To know the differences between equals and == operator go through this link: Difference between "equals" and "==" operator

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26