2012-04-01 62 views
0

我有一個名爲ReadTill的方法,它具有相同的代碼體但參數類型不同。有人可以給我看一個策略/代碼來合併它們。我不認爲InputStreamBufferedReader共享一個接口,如果他們這樣做,它是什麼,如果他們不怎麼做我會怎麼做?Java複製方法合併

我認爲這個問題應該是,我如何用泛型來做到這一點?

在此先感謝。

public static void ReadTill(InputStream in, OutputStream out, String end) throws IOException { 
    int c, pos = 0; 
    StringBuffer temp = new StringBuffer(); 
    while ((c = in.read()) != -1) { 
     char cc = (char) c; 
     if (end.charAt(pos++) == cc) { 
      if (pos >= end.length()) { 
       break; 
      } 
      temp.append(cc); 
     } else { 
      pos = 0; 
      if (temp.length() > 0) { 
       out.write(temp.toString().getBytes()); 
       temp.setLength(0); 
      } 
      out.write(cc); 
     } 
    } 
} 

public static void ReadTill(BufferedReader in, OutputStream out, String end) throws IOException { 
    int c, pos = 0; 
    StringBuffer temp = new StringBuffer(); 
    while ((c = in.read()) != -1) { 
     char cc = (char) c; 
     if (end.charAt(pos++) == cc) { 
      if (pos >= end.length()) { 
       break; 
      } 
      temp.append(cc); 
     } else { 
      pos = 0; 
      if (temp.length() > 0) { 
       out.write(temp.toString().getBytes()); 
       temp.setLength(0); 
      } 
      out.write(cc); 
     } 
    } 
} 
+0

爲什麼你想在這裏使用泛型?當方法參數或變量實際上實際上是一個對象,但是被訪問就好像它是用特定的類來鍵入的時候,泛型被用於這種情況。你的情況沒有這樣的變數。 – 2012-04-01 06:23:30

+0

@AlexeiKaigorodov理由: A)想清理代碼,認爲他們會 B)看看他們將如何用於教育目的。 – 2012-04-01 07:15:07

回答

2

這些類(InputStreamBufferedReader)沒有實現相同的接口,也延長了同一類,但你可以創造一個從其他:

public static void readTill(InputStream in, OutputStream out, String end) throws IOException { 
    readTill(new BufferedReader(new InputStreamReader(in)), out, end); 
} 

public static void readTill(BufferedReader in, OutputStream out, String end) throws IOException { 
    // as before 
} 

通常,Java方法名稱是camelCase,所以我在示例中對其進行了更改。

+0

你知道我可以用泛型做到嗎? – 2012-04-01 04:15:21

+1

由於我在答覆頂部寫的原因,我不確定這是可能的。 – MByD 2012-04-01 04:16:28

1

只是把我的頭頂部,未經測試:

public static void ReadTill(InputStream in, OutputStream out, String end) throws IOException { 
ReadTill(new BufferedReader(new InputStreamReader(in)), out, end); 
}