classB と classC の 2 つのクラスがあり、どちらも classLetters を拡張しています。classB と classC が呼び出す別のクラスには、getBType() と getCType() の 2 つのメソッドがあります。2 つのコードはほぼ重複しています。1 つは B 型を取得し、もう 1 つは C 型を取得することを除いて、どちらも同じことを行うためです。これら 2 つを getType(String className) と呼ばれる単一のメソッドに結合する方法はありますか?たとえば、どのクラスがそれを呼び出しているかを検出し、メソッドを呼び出した人に応じて正しい型を取得できますか? これは、classB から getBType() を呼び出し、classC から getCType() を呼び出す代わりに、getType(String className) という 1 つのメソッドだけで classB または classC から呼び出すことができるようにするためです。これから拡張するクラスをさらに多く追加し、重複するコードの量を減らしたいので、これは重要です。
Collection<classB> bstuff = new Collection<classB>();
Collection<classC> cstuff = new Collection<classC>();
public Collection<classB> getBType() {
ArrayList<classB> b = new ArrayList<classb>(); //this can just return bstuff instead
b.addAll(bstuff); //but i would like to leave this here for the example
return b;
}
public Collection<classC> getCType() {
ArrayList<classC> c = new ArrayList<classc>(); //this can just return cstuff instead
c.addAll(cstuff); //but i would like to leave this here for the example
return c;
}
クラスによってインデックス付けされたコレクションを保持するデータ構造を作成します。
static HashMap<String, Collection<? extends classLetters>> allLetters = new HashMa..... etc(); //just an example
//then here i would statically add each class type to the hashmap
public Collection<? extends classLetters> getType(className) {
if (className == "classB") {
ArrayList<classB> b = new ArrayList<classb>();
b.addAll(bstuff);
return b;
}
else if (className == "classC") {
ArrayList<classC> c = new ArrayList<classc>();
c.addAll(cstuff);
return c;
}
}
ただし、これにはまだ重複したコードが含まれています。ジェネリックを使用することは可能ですか?
public <T> Collection<T> getType() {
ArrayList<T> anyLetter = new ArrayList<T>;
anyLetter.addAll(/* somehow distingush which letter class to put here */);
return anyLetter;
}