简体   繁体   English

用Java动态生成对象

[英]Dynamic generation of objects in java

HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();
for (String regionCode : outScopeActiveRegionCodeSet) {
    //code required
}   

Here i need to create new TransactionLOgDTO objects dynamically insed the loop like below.If there are 3 regioncodes in hashset i need 3 TransactionLOgDTO objects with regionCode appended to name of new object. 在这里,我需要创建一个新的TransactionLOgDTO对象,以动态方式插入如下所示的循环。如果哈希集中有3个区域代码,则我需要3个TransactionLOgDTO对象,并在新对象的名称后附加regionCode。

TransactionLOgDTO regionCode1DTO=new TransactionLOgDTO(); 

}

I need something like this to be done........................... 我需要做这样的事情...........................

for (String regionCode : outScopeActiveRegionCodeSet) { TransactionLOgDTO "regionCode"+DTO=new TransactionLOgDTO(); } 

I would recommend using an ArrayList instead of putting the index in the variable name: 我建议使用ArrayList而不是将索引放在变量名中:

List<TransactionLOgDTO> regionCodeDTOs = new ArrayList<TransactionLOgDTO>();
HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();
for (String regionCode : outScopeActiveRegionCodeSet) {
    regionCodeDTOs.add(new TransactionLOgDTO());
}   

or, since you aren't using the regionCode String: 或者,因为您没有使用regionCode字符串:

List<TransactionLOgDTO> regionCodeDTOs = new ArrayList<TransactionLOgDTO>();
HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();
for (int i = 0; i < outScopeActiveRegionCodeSet.size(); i++) {
    regionCodeDTOs.add(new TransactionLOgDTO());
}

Then you can access them using: 然后,您可以使用以下命令访问它们:

regionCodeDTOs.get(i);

[EDIT] [编辑]
If you want to connect the regionCode to the TransactionLogDTO I would recommend a Map instead : 如果要将regionCode连接到TransactionLogDTO ,则建议使用Map instead

Map<String, TransactionLOgDTO> transactionCodeDTOs = new HashMap<String, TransactionLOgDTO>();
HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();
for (String regionCode : outScopeActiveRegionCodeSet) {
    transactionCodeDTOs.put(regionCode, new TransactionLOgDTO());
}

which are retrieved like: 像这样检索:

transactionCodeDTOs.get(regionCode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM