我想使用indexOf
方法來查找字符串中的字數和字母數。將泛型類型傳遞給indexOf方法JAVA
的indexOf方法可以接受:
indexOf(String s)
indexOf(Char c)
indexOf(String s, index start)
因此該方法可以接受字符串或人物,也可以接受起點
我希望能夠通過其中一個String或一個字符到這個方法,所以我試圖使用泛型。下面的代碼是主要的和2個功能。正如你所看到的,我希望能夠讓indexOf與我傳入的字符串或字符一起工作。如果我在indexOf中將's'強制轉換爲字符串,它將起作用,但當它嘗試以Char形式運行時會崩潰。非常感謝!
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;
}
方法重載根本無法這樣工作。三個獨立的'indexOf'方法基本上是無關的,所以你不能使用泛型智能地調用其中一個。 – ruakh 2013-02-18 18:16:43
Ahh gosh基本上不可能吧?除非有可能檢查通用對象的類型,然後如果(String)然後執行indexOf((String)s,index)&if(Char)then indexOf((Char)s,index) – nearpoint 2013-02-18 18:19:34