異なるタイプのオブジェクトをリンクリストに格納しようとしています。私はProtoType
から継承するいくつかのユニークな "タイプ"クラスを持っています(ここでは1つしか表示されていません、一緒に5つのタイプがあります)。継承を使用して作成したオブジェクトをリンクリストに追加してそのメソッドを実装する
私は新しいオブジェクトを作成するときに、 "type1.someMethods"を使ってその中のすべてのメソッドにアクセスできます。私が知らないのは、リストを反復して、リスト内の位置に基づいて異なる "タイプ"のそれぞれのメソッドを取得する方法です。私は「typeList.get(int型のインデックス).someMethods()を使用することができるだろうと思った。私は唯一のLinkedListに関連付けられているメソッドを使用することができるよ。
親クラス
public class ProtoType {
private int ID;
private int x;
private String type;
private int randomNumber;
public ProtoType(int ID, int x, String type) {
this.ID = ID;
this.x = x;
this.type = type;
this.randomNumber = randomNumber;
}
public int getID() {
return ID;
}
public int getX() {
return x;
}
public void randomNumberGenerator(int max, int min) {
Random r = new Random();
randomNumber = r.nextInt(max - min + 1) + 1;
}
public int getRandomNum() {
return randomNumber;
}
}
子供クラス
public class Type1 extends ProtoType {
public Type1(int ID, int x, String type) {
super(ID, x, type);
}
public void preformAction(){
System.out.println(getRandomNum());
switch (getRandomNum()){
case 1:
case 2:
//Some action
break;
case 3:
//some action
break;
case 4:
//some action
break;
}
}
}
メインクラス
import java.util.LinkedList;
public class TestMAin {
public static void main(String[] args) {
LinkedList typeList = new LinkedList();
Type1 t1 = new Type1(1, 12, "type1");
typeList.add(0, t1);
Type1 t2 = new Type1(2, 13, "type1");
typeList.add(1, t2);
}
//////////////
// the issue
//iterate thru the array get the type
//implement the methods of that type
/////////////
}
あなたはそれがどのような方法で実装されているか知りたいですか?なぜあなたはそれがどのクラスのインスタンスであるかを確認するだけではないのですか? –
これは機能要求でラップされた設計エラーです。実際に何をしようとしていますか?型付けされていないオブジェクトのリストを持つよりはるかに良い方法があります。 – Voo
最後に、リストをループする必要があり、オブジェクトに基づいて、特定のメソッドを実装する必要があります。したがって、私がインデックス12にいる場合は、オブジェクトタイプを取得し、そのタイプに基づいて特定のアクションを実装します。私はいくつかのインスタンスに沿って移動すると削除され、他は追加されます。私は、さまざまなインスタンスの取得と削除を保存し、そのメソッドを実装する方法が必要です。 – user3137110