首页
IT
登录
6mi
u
盘
搜
搜 索
IT
我的笔记 HashMap 集合类
我的笔记 HashMap 集合类
xiaoxiao
2021-04-14
30
import
java.util.*;
public
class
HashMap1 {
public
static
void
main(String[] args)
{
HashMap
cc=
new
HashMap
();
Sp sp1=
new
Sp(
"001"
,
"薯片"
,5);
Sp sp2=
new
Sp(
"002"
,
"话梅"
,6);
Sp sp3=
new
Sp(
"003"
,
"面包"
,3);
cc.put(
"001"
,sp1)
;
// 键 值
cc.put(
"002"
,sp2)
;
cc.put(
"003"
,sp3)
;
if
(cc.containsKey(
"002"
))
//不需要遍历
{
System.
out
.println(
"该食品信息为"
);
Sp sp=(Sp)cc.get(
"002"
);
System.
out
.println(sp.getName());
System.
out
.println(sp.getJiage());
}
else
{
System.
out
.println(
"没有该食品"
);
}
/* for(
int
i=0;i<cc.size();i++)
{
cc.get(i)
}
for循环不行 应为get()的i是一个字符串
*/
Iterator
it=cc.keySet().iterator();
//keySet() 键值设置 激活所有键值 取出
while
(it.hasNext())
//hasNext() 还有没有下一个键值?有true 没有false
{
String key=it.next().toString();
//it.next()接收下一个键值toString()转化为字符串
Sp sp=(Sp)cc.get(key);
System.
out
.println(
"食品名称:"
+sp.getName());
System.
out
.println(
"食品价格:"
+sp.getJiage());
}
}
}
当键值 为类时 则要根据需要 改写equals和hashcode的方法
import
java.util.HashMap;
import
java.util.Iterator;
import
java.util.Set;
public
class
txt1
{
public
static
void
main(String[] args )
{
HashMap
hs=
new
HashMap
();
wouitl t1=
new
wouitl(
"小明"
,1);
wouitl t2=
new
wouitl(
"小明"
,2);
wouitl t3=
new
wouitl(
"小红"
,1);
wouitl t4=
new
wouitl(
"小红"
,2);
hs.put(t1, 1)
;
hs.put(t2, 2)
;
hs.put(t3, 3)
;
hs.put(t4, 4)
;
Set
key=hs.keySet();
Iterator
it=key.iterator();
while
(it.hasNext())
{
wouitl i=(wouitl) it.next();
System.
out
.println(hs.get(i));
}
}
}
class
wouitl
{
String
name
;
int
geshu
;
public
String getName() {
return
name
;
}
public
void
setName(String name) {
this
.
name
= name;
}
public
int
getGeshu() {
return
geshu
;
}
public
void
setGeshu(
int
geshu) {
this
.
geshu
= geshu;
}
public
wouitl(String name,
int
geshu)
{
this
.
name
=name;
this
.
geshu
=geshu;
}
public
boolean
equals(Object obj)
{
boolean
res=
false
;
if
(
this
==obj)
{
res=
true
;
}
if
(obj
instanceof
wouitl)
{
if
(
this
.getName().equals(((wouitl) obj).getName()))
{
res=
true
;
}
}
return
res;
}
public
int
hashCode()
{
return
this
.getName().hashCode();
}
}
转载请注明原文地址: https://ju.6miu.com/read-669755.html
技术
最新回复
(
0
)