2013-02-18 120 views
1

我想使用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; 
} 
+1

方法重載根本無法這樣工作。三個獨立的'indexOf'方法基本上是無關的,所以你不能使用泛型智能地調用其中一個。 – ruakh 2013-02-18 18:16:43

+0

Ahh gosh基本上不可能吧?除非有可能檢查通用對象的類型,然後如果(String)然後執行indexOf((String)s,index)&if(Char)then indexOf((Char)s,index) – nearpoint 2013-02-18 18:19:34

回答

2

String.indexOf不使用泛型。它需要特定類型的參數。您應該使用重載的方法。因此:

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

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

Yah把它當作一種重載的方法,但只是想看看我是否可以這樣做。但經過一些研究後,似乎不可能用indexOf方法,它不會指望泛型 – nearpoint 2013-02-18 18:22:11

+0

非常感謝答案! – nearpoint 2013-02-18 18:22:28

相關問題