0

The code seems correct and straight forward to me, I'm using the basic indexOf method for an array i created.

Why won't this code:

public int indexOf(X s)
{        
    for (int i = 0; i <= arr.length-1; i++)
    {
        if (arr[i] == s)
        {
            return i;
        } 
    }        
    return -1;
}

pass this test:

@Test
public void testIndexOf()
{
    BetterArray<String> b = new BetterArray<String>();

    for (int i = 0; i < 20; i++)
        b.add("str" + i);

    assertEquals(0, b.indexOf("str0"));
    assertEquals(19, b.indexOf("str19"));
    assertEquals(-1, b.indexOf("not found"));
}
Jakkie Chan
  • 317
  • 4
  • 14

1 Answers1

1

Cause you compare String or any other object equality with equals() not with ==.

== tests for reference equality.

.equals() tests for value equality.

Read more : How do I compare strings in Java?

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53