[英]accesing attribute of anobject from another object that belong to the same class
嗨,我對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。 我的問題是如何從DailyAssessmentReport
類訪問/獲取Auctioneer.configuration
價值?
非常感謝您的回答
您可以使用地圖,例如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];
我希望這可以幫助你。 如果不是,例如因為我誤解了您的問題,請提供反饋,以便我們為您找到合適的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.