ogward
ogward

Reputation: 1193

Linear array search

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;
    }

Upvotes: 0

Views: 1686

Answers (5)

xmedeko
xmedeko

Reputation: 7812

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.

Upvotes: 1

Dirk
Dirk

Reputation: 31053

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.

Upvotes: 0

Chris Morgan
Chris Morgan

Reputation: 2080

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.

Upvotes: 3

Olaf
Olaf

Reputation: 6289

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

Upvotes: 0

Lirm
Lirm

Reputation: 413

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

Upvotes: 1

Related Questions