[英]java hashmap with a class value
我需要將TDSContent
存儲到指定String
鍵的哈希圖中。 我需要做這樣的事情。
public class Target {
public Target() {
final int a = 0x64c896;
final int b = 0xc050be;
final int c = 0xffc896;
TDS = new HashMap<String, TDSContent>();
TDSContent contentMA = new TDSContent(a, b, c, 10);
TDSContent contentMB = new TDSContent(a, c, b, 10);
TDSContent contentMC = new TDSContent(b, a, c, 10);
TDSContent contentMD = new TDSContent(c, b, a, 10);
TDSContent contentME = new TDSContent(c, a, b, 10);
TDSContent contentMF = new TDSContent(b, c, a, 10);
... // and so on...
TDS.put("Marker A", contentMA);
TDS.put("Marker B", contentMB);
TDS.put("Marker C", contentMC);
TDS.put("Marker D", contentMD);
TDS.put("Marker E", contentME);
TDS.put("Marker F", contentMF);
... // and so on...
}
public int getCL(String key) {
TDSContent tdc = TDS.get(key);
if(tdc.equals(contentMA)) {
return contentMA.getValue();
} else if(tdc.equals(contentMB)) {
return contentMB.getValue();
} else if(tdc.equals(contentMC)) {
return contentMC.getValue();
} else if(tdc.equals(contentMD)) {
return contentMD.getValue();
} else if(tdc.equals(contentME)) {
return contentME.getValue();
} else if(tdc.equals(contentMF)) {
return contentMF.getValue();
} ...// and so on...
else {
return contentMD.getValue();
}
}
}
問題是,手動創建類TDSContent
的對象將需要大量的工作。
我可以做這樣的事情嗎...:
public class Target {
public Target() {
final int a = 0x64c896;
final int b = 0xc050be;
final int c = 0xffc896;
TDS = new HashMap<String, TDSContent>();
// form: new TDSContent(CL, CM, CR, D);
TDS.put("Marker A", new TDSContent(a, b, c, 10));
TDS.put("Marker B", new TDSContent(a, c, b, 10));
... // and so on..
}
public int getCL(String key) {
// this method gets the first parameter of the TDSContent
// constructor (see comment above).
return TDS.get(key).getValue();
}
public int getCM(String key) {
... // similar to getCL but returns the second parameter of the TDSContent
// constructor (see comment above)
...在getCL()
,獲取和getCL()
的實例化[?]值?
具體來說,如果我打電話給類似的人:
Target target = new Target();
int x1 = target.getCL("Marker A"); // I should get 0x64c896 here
int x2 = target.getCM("Marker A"); // I should get 0xc050be here
那可能嗎?
當然,只要匹配您在映射到訪問器的TDSContent
對象上調用的getXXX()
方法即可。 假設您在每個構造函數參數的TDSContent
上都有訪問器。
public int getCL(String key) {
return TDS.get(key).getCL();
}
public int getCM(String key) {
return TDS.get(key).getCM();
}
public int getCR(String key) {
return TDS.get(key).getCR();
}
public int getD(String key) {
return TDS.get(key).getD();
}
無論您是否將其分配給變量作為中間步驟,都是TDSContent
。
我不太了解getCL
的第一個實現的getCL
,似乎完全破壞了首先擁有地圖的目的。 (我看不到TDS
在哪里聲明,僅在分配。)
我可能會更進一步,並創建一些方便的實用程序方法,以使事情變得更短,即使它們很多。
putTds("Marker B", tds(a, c, b, 10));
創建getCL
和getCM
helper方法的想法很不錯,可以大大提高程序的可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.