使用java中的循环填充hashmap
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用java中的循环填充hashmap,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1930字,纯文字阅读大概需要3分钟。
内容图文
![使用java中的循环填充hashmap](/upload/InfoBanner/zyjiaocheng/783/14df198e79b7450aacb276a4fd9af062.jpg)
嗨,我有一个问题用循环填充hashmap,我需要将对象存储为值和字符串作为键,如果另一个元素想要添加到hashmap,则应该检查它,如果该值已经存在,如果是这样,它应该例如,将字符串键增加1:
("JButton", JButtonObject);
如果JButton应该是另一个元素想要添加
("JButton1", JButtonObject);
...
...
...
我的代码:
多谢你们
private void CreateInstance(java.awt.event.ActionEvent evt) {
// add code here
Object object = null;
if (evt.getSource() == CreateInstance)
{
int[] selectedIx = ClassList.getSelectedIndices();
for (int i=0; i<selectedIx.length; i++) {
Object sel = ClassList.getModel().getElementAt(selectedIx[i]);
try {
Class classDefinition = Class.forName(sel.toString());
object = classDefinition.newInstance();
//create name
String data = sel.toString();
String substring = data.substring(12);
//check if name is unique
//add to map
hm.put(substring, object);----- HERE IS THE PROBLEM
System.out.println();
}
catch (InstantiationException e) {
System.out.println(e);
}
catch (IllegalAccessException e) {
System.out.println(e);
}
catch (ClassNotFoundException e) {
System.out.println(e);
}
if(object instanceof java.awt.Component){
DesignWindow.add((java.awt.Component)object);
DesignWindow.validate();
}
else{
System.out.println("Error");
}
}
}
}
解决方法:
也许你应该使用另一种结构,正如每个人所说.但是为了做你想做的事:
String substring = data.substring(12);
//check if name is unique
// add this line
String uniqueKey = findUniqueKey(hm, substring);
//add to map with the calculated value
hm.put(uniqueKey, object);----- HERE IS THE PROBLEM
和…
private String findUniqueKey(Map<String, ?> map, String prefix)
{
if (!map.containsKey(prefix))
return prefix;
int i = 1;
while(true) { // or check i against a maximum
String candidate = prefix + i;
if (!map.containsKey(candidate))
return candidate;
i++;
}
}
这样,您就可以将用于确定密钥的逻辑与其余代码分开.
旁注:尝试使用地图参考.仅使用HashMap创建实例.因此,您的代码不会与您需要的特定实现相关联:Map.
内容总结
以上是互联网集市为您收集整理的使用java中的循环填充hashmap全部内容,希望文章能够帮你解决使用java中的循环填充hashmap所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。