请问arraylist的元素跟hashmap的索引值一样是不是就能够通过元素索引获取到hashmap的key跟value呢??

viranc 2017-03-31 09:56:55
//买一副牌
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"方片","梅花","红桃","黑桃"};
HashMap<Integer, String> hm = new HashMap<>(); //存储索引和扑克牌
ArrayList<Integer> list = new ArrayList<>(); //存储索引
int index = 0; //索引的开始值
for(String s1 : num) {
for(String s2 : color) {
hm.put(index, s2.concat(s1)); //将索引和扑克牌添加到HashMap中
list.add(index); //将索引添加到ArrayList集合中
index++;
}
}
hm.put(index, "小王");
list.add(index);
index++;
hm.put(index, "大王");
list.add(index);
//洗牌
Collections.shuffle(list);
//发牌
TreeSet<Integer> gaojin = new TreeSet<>();
TreeSet<Integer> longwu = new TreeSet<>();
TreeSet<Integer> me = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>();

for(int i = 0; i < list.size(); i++) {
if(i >= list.size() - 3) {
dipai.add(list.get(i)); //将list集合中的索引添加到TreeSet集合中会自动排序
}else if(i % 3 == 0) {
gaojin.add(list.get(i));
}else if(i % 3 == 1) {
longwu.add(list.get(i));
}else {
me.add(list.get(i));
}
}

//看牌
lookPoker("A", gaojin, hm);
lookPoker("B", longwu, hm);
lookPoker("C", me, hm);
lookPoker("底牌", dipai, hm);

}

public static void lookPoker(String name,TreeSet<Integer> ts,HashMap<Integer, String> hm) {
System.out.print(name + "的牌是:");
for (Integer index : ts) {
System.out.print(hm.get(index) + " ");
}

System.out.println();


------------------------------------分割线---------------------------------------------------------
请问arraylist的索引值跟hashmap的索引值一样就能够通过索引值获取到hashmap的key跟value呢??

HashMap<Integer, String> hm = new HashMap<>(); //存储索引和扑克牌
ArrayList<Integer> list = new ArrayList<>(); //存储索引
...全文
187 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
as小詹 2017-04-01
  • 打赏
  • 举报
回复
arraylist集合的元素值可以重复,hashmap集合的key值是不能重复的 程序中的index承担了arraylist的值,也承担了hashmap的key,所以arraylist的index值可以获取到hashmap的value

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧