Joe Perkins
Joe Perkins

Reputation: 271

returning the position of an array

I am trying to create a find method, that will check every entry in my PhoneDirectory, and return the position of the name that matches the name given in the parameter. This is what currently have:

private String find(String name) {
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            return x.getName();
        }
    }

    return null;
}

However I will be calling my find function from within other methods that don't necessarily want the name returned, but instead the number attached to the name, (each DirectoryEntry has a name and a telno). Any help regarding how to return the position of the array instead of just the matching name, would be much appreciated.

Upvotes: 0

Views: 89

Answers (5)

Norbert Radyk
Norbert Radyk

Reputation: 2618

Why not to avoid reinventing the wheel and use Guava instead:

private int find(String name) {
    return Iterables.indexOf(theDirectory, new Predicate<DirectoryEntry>() {
        public boolean apply(DirectoryEntry de) {
            return de.getName().equals(name);
        }
    });
}

Upvotes: 0

LionC
LionC

Reputation: 3106

Depending on the type of your theDirectory-field you could use an own counter up to its length:

private int find(String name) {
    for (int i = 0; i < theDirectory.length(); i++) {
        DirectoryEntry x = theDirectory[i]; //If it is an Array; for Lists use get etc...
        if (x.getName().equals(name)) {
            return i;
        }
    }

    return -1;
}

Upvotes: 0

anirudh
anirudh

Reputation: 4176

If you want the position in the array, use a regular loop instead of a foreach loop.

for (int i=0;i<theDirectory.length;i++) {
DirectoryEntry x = theDirectory[i];
    if (x.getName().equals(name)) {
        return i;
    }
}

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3820

private String find(String name) {
    int k=0;
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            k++;
            return x.getName();
        }
    }
//k will give you pos
    return null;
}

Upvotes: 1

stinepike
stinepike

Reputation: 54672

you can take a couter to count the postion

private int find(String name) {
    int i = 0;
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            return i;
        } 
        i++;
    }

    return -1;  // returning -1 if not found
}

or you can use normal for loop instead of foreach

Upvotes: 3

Related Questions