2013-02-18 1 views
1

indexOf 메서드를 사용하여 문자열의 단어 수와 문자를 찾습니다.일반적인 형식을 indexOf 메서드에 전달 JAVA

같이 IndexOf 방법은 받아 들일 수 :

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

그래서 방법이 또는 문자문자열을 받아 들일 수 있고 받아 들일 수 시작 지점 나는 할 수 있도록하려면

는 문자열 중 하나를 전달하는 또는 Character를이 메서드에 추가하여 제네릭을 사용하려고했습니다. 아래 코드는 main과 2 개의 함수입니다. 당신이 볼 수 있듯이 내가 전달하는 String 또는 Character로 indexOf 작업을 수행 할 수 있기를 원합니다. indexOf에서 String으로 캐스팅하면 작동하지만 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' 메소드는 본질적으로 서로 관련이 없으므로 지능형으로 하나 또는 다른 것을 호출하는 데 generics를 사용할 수 없습니다. – ruakh

+0

Ahh gosh 그래서 기본적으로 가능하지 않니? if (String), if (Char) then indexOf ((Char) s, index) – nearpoint

답변

2

String.indexOf은 제네릭을 사용하지 않습니다. 특정 유형의 매개 변수를 사용합니다. 오버로드 된 메서드를 대신 사용해야합니다. 따라서 :

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

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

Yah I 원래는 클래스의 어떤 유형이 일반 객체인지 검사 할 수 없다면 indexOf ((String) s, index) 오버로드 된 방법으로 사용했지만이 방법으로 처리 할 수 ​​있는지 알고 싶었습니다. 그러나 제네릭 형식을 기대하지 않는 indexOf 메서드를 사용하면 약간의 연구가 가능하지 않은 것처럼 보입니다. – nearpoint

+0

답변 해 주셔서 감사합니다! – nearpoint