2016-09-23 5 views
0

私はWorldOfRobotsとRobot(abstract)という2つのクラスを持っています。どちらも公開です。ロボットの世界は基本的にロボットのarraylistです。 それから、私はロボットの延長線上にあるクラステレボットを持っています。 私は現在のオブジェクトTelebotがあるロボットのリストを識別し、取得するメソッドTelebotでメソッドを構築しようとしています。 例: 2つのWorld of Robots(wor1とwor2)と1つのtelebot(r1)を作成します。 wor1にr1を追加します。 私は、クラスtelebotのメソッドでwor1のロボットのリストを取得する方法を取得したいと思います。Java他のクラスからオブジェクトのリストを取得

ここにコードがあります。

abstract class Robot { 
// content 
} 

public class Telebot extends Robot 
{ 
    // instance variables - replace the example below with your own 
    private WorldOfRobots wor; 

    public Telebot(String newName, String newDirection) 
    { 
     super(newName, newDirection); 
    } 

    public void something { 

     // here I'm trying to get the list 
     wor = new WorldOfRobots(); 
     ArrayList<Robot> robots = wor.getList(); 
     // Unfortunately this solution doesn't work cause I'm creating a new WOR. What I want is to get the WOR where the Telebot belong. 
    } 

} 

public class WorldOfRobots { 

// List of robots 
private ArrayList<Robot> robots; 

    public WorldOfRobots() { 
    robots = new ArrayList<Robot>(); 
    } 

    public ArrayList<Robot> getList() { 
     return robots; 
    } 

} 

ありがとうございました。

+0

'WorldOfRobots wor'という追加パラメータを' Telebot'コンストラクタに渡してそこに割り当てることができます。 – SomeJavaGuy

+0

私はここでサイクリック依存関係を嗅いでいますが、多分あなたはテレボのクラスでworの使用法についてあなたのユースケースを詳しく説明することができます。テレボットとロボットの世界の関連で何を達成したいですか? – Sikorski

+0

ロボットのリストをループして、テレボットがいくつかの属性を別のものと共有しているかどうかを確認したいと思います。通常、WoRは1つしかなく、複数のロボットを追加することができます。 – Cephou

答えて

0

あなたは私はあなたのクラスはまさに私がこの方法を使用して展開することはできませんので、相互作用しているかわからないrobotInstance.something(listOfRobot); を呼び出すことができる外部のクラスから今...このような何かに

public class Telebot extends Robot { 

//your code and constructer here 

public void something(WorldofRobots container){ 
    //this is the list containing your instance of telerobot, use it as you like 
} 

} 

をあなたのクラスをリファクタリングすることができますもっと。 RobotクラスのWorldOfRobotsための参照を格納

0
abstract class Robot { 
private WorldOfRobots world; 

public void setWorld(WorldOfRobots world) 
{ 
    this.world=world; 
} 
// content 
} 

public class Telebot extends Robot 
{ 
    public Telebot(String newName, String newDirection) 
    { 
     super(newName, newDirection); 
    } 
    public void doSomething() 
    { 
     world.doSomethingElse(); 
    } 

} 

public class WorldOfRobots { 

// List of robots 
private ArrayList<Robot> robots; 

    public WorldOfRobots() { 
    robots = new ArrayList<Robot>(); 
    } 
    public void addRobot(Robot robot) 
    { 
     robots.add(robot); 
     robot.setWorld(this); 
    } 

} 

は、この場合には妥当です。ロボットを複数のWorldOfRobotsに所属させたい場合は、ワールド変数をリストに変更してください。

関連する問題