0

嗨,我在 OOP 方面不是很好,对不起,如果有人问过同样的问题。现在我在从另一个对象访问一个对象的属性时遇到问题,其中两个对象都属于一个对象

public abstract class GameClient (){  
protected ClientRegistry registry;  
..   
}


public class MarketClient extends GameClient {   
public Auctioneer auctioneer = null;  
public Specialist specialist;  
...  
((GenericDoubleAuctioneer) auctioneer).setRegistry((MarketRegistry) registry);
specialist = registry.addSpecialist(clientId);  
}


public class Specialist extends AccountHolder() {  
public Specialist(final String id) {
        this(id, null);  
...   
}


public interface Auctioneer extends QuoteProvider (){  
public MarketRegistry getRegistry();  
public List configuration  
...  }

  public class DailyAssessmentReport(){  
protected void calculateProfits() {  
final Specialist specialists[] = GameController.getInstance().getRegistry().getSpecialists();  
//later, I'll get the ID of each specialist from specialists[];  
...  
...  
public Map< specialistID, List, Score> Result;  
//this Map contains specialistID , auctioneer.configuration, score  
}

我想做的是制作一个包含(specialistID、auctioneer.configuration、profit)的MAP。我的问题是如何访问/ Auctioneer.configurationDailyAssessmentReport类中获取价值?

我真的很感谢你的回答

4

1 回答 1

0

您可以使用地图,例如 HashMap 来达到您的目的。请注意,映射从一个对象映射到另一个对象。它们不会像您在示例中尝试做的那样从一个对象映射到其他两个对象。但是,您仍然可以通过将两个目标对象存储在一个公共容器对象(例如 ArrayList 或 2 元素数组)中然后映射到容器对象来实现您的目标。例子:

HashMap<String, Object[]> specialistIdToContainerObjectMap = new HashMap<String, Object[]>();

// get two objects which should be looked up later through the map, based on specialist ID
Specialist specialist = ...;
Auctioneer auctioneer = ...;

// create container object to hold the two objects to which we want to map
Object[] containerObject = new Object[2];
containerObject[0] = specialist;
containerObject[1] = auctioneer;

// store the container object in the map
specialistIdToContainerObjectMap.put(specialist.getId(), containerObject);

然后,您可以稍后查找容器对象并从中提取两个引用的对象:

// get a specialist id from somewhere, e.g. by doing someSpecialist.getId()
String specialistId = ...;

// look up the container object from the map
Object[] containerObject = specialistIdToContainerObjectMap.get(specialistId);

// extract the specialist and the auctioneer from the container object
Specialist specialist = (Specialist) containerObject[0];
Auctioneer auctioneer = (Auctioneer) containerObject[1];

我希望这可以帮助你。如果不是,例如因为我误解了您的问题,请提供反馈,以便我们尝试为您找到正确的解决方案。

于 2012-11-26T18:17:09.723 回答