Nearpoint
Nearpoint

Reputation: 7362

Passing Generic Type into indexOf method JAVA

I want to use the indexOf method to find the number of words, and letters in a String.

indexOf method can accept:

indexOf(String s)
indexOf(Char c)
indexOf(String s, index start) 

So the method can accept Strings or Characters and can also accept starting point

I want to be able to pass either a String or a Character into this method so I have tried to use generics. The code below is main and 2 functions. As you can see I want to be able to have indexOf work with String or Character that I pass in. If I cast 's' in indexOf to a String, it works, but then crashes when it tries to run as Char. Thanks so much in advance!

public static void main(String[] args) {
    MyStringMethods2 msm = new MyStringMethods2();
    msm.readString();
    msm.printCounts("big", 'a');
}

public <T> void printCounts(T s, T c) {
    System.out.println("***************************************");
    System.out.println("Analyzing sentence = " + myStr);
    System.out.println("Number of '" + s + "' is " + countOccurrences(s));

    System.out.println("Number of '" + c + "' is " + countOccurrences(c));
}

public <T> int countOccurrences(T s) {
    // use indexOf and return the number of occurrences of the string or
    // char "s"
    int index = 0;
    int count = 0;
    do {
        index = myStr.indexOf(s, index); //FAILS Here
        if (index != -1) {
            index++;
            count++;
        }
    } while (index != -1);
    return count;
}

Upvotes: 1

Views: 570

Answers (1)

Eric Galluzzo
Eric Galluzzo

Reputation: 3241

String.indexOf does not use generics. It takes specific types of parameters. You should use overloaded methods instead. Thus:

public int countOccurrences(String s) {
    ...
}

public int countOccurrences(char c) {
    return countOccurrences(String.valueOf(c));
}

Upvotes: 2

Related Questions