【发布时间】:2012-04-01 04:10:02
【问题描述】:
我有一个名为ReadTill 的方法,它具有相同的代码主体但参数类型不同。有人可以告诉我一个策略/代码来组合它们。我不认为InputStream 和BufferedReader 共享一个界面,如果他们这样做,它是什么,如果他们不这样做,我会怎么做?
我认为问题应该是,如何使用泛型来做到这一点?
提前致谢。
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);
}
}
}
【问题讨论】:
-
为什么要在这里使用泛型?泛型用于方法参数或变量实际上接受一个对象但被访问的情况,就好像它是使用特定类键入的一样。在你的情况下没有这样的变量。
-
@AlexeiKaigorodov 原因:A) 想清理代码,认为他们会 B) 看看它们将如何用于教育目的。