我的笔记 HashMap 集合类

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();
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值