0

I'm pretty new to java and I'm trying to learn so I'm just wondering how I could preform a linear search through my array. This is what I've done so far but it doesn't work.

public boolean contains(Object elem)
    {
        boolean result = false;
        for(int i=0;i<this.vector.length;i++)
            if(elem.equals(this.vector[i]))
                result=true;
            else
                result=false;
        return result;
    }

    public int indexOf(V elem)
    {
        int pos = 0;
        for(int i=0;i<this.vector.length;i++)
            if(this.vector[i].equals(elem))
                pos=i;
            else
                pos= -1;
        return pos;
    }
1
  • Can you show us how it fails? An example, maybe. Commented May 19, 2011 at 16:37

5 Answers 5

3

Your contains() function only returns true if the passed elem is the last item in the array. If you find it, you should return true immediately.

Your indexOf() method suffers from the same issue.

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

1 Comment

@ogward Accepting the answer would be very nice ;)
1

You're missing a break after you've found the element.

Comments

1

Oneliner:

Arrays.asList(vector).indexOf(elem);

It just creates and deletes one more object (ArrayList) in the memory. Should not be a problem in the most of situations.

Comments

0

You need to break your loop when you find your match.

Comments

0

There are a few problems with that code: in both methods, you always search through the entire array, even if you have found the element already. In both methods, this is the source of a bug (and less importantly: it is not as efficient as it could be).

for(int i=0;i<this.vector.length;i++)
    if(elem.equals(this.vector[i]))
       return true;
return false;

(and similar for the other method) might be a better implementation.

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.