Map和hashMap

2016-09-19  本文已影响28人  少冰三hun甜

![Upload Paste_Image.png failed. Please try again.]

java集合框架基础概念
List/set接口及实现类——ArrayList/hashSet
Map和hashMap##Map接口

1.Map提供了一种映射关系,其中的元素是以键值对(key - value)的形式存储的,能够实现根据key快速查找value
2.Map中的键值对以Entry类型的对象实例形式存在
3.键(key值)不可重复,value值可以重复
4.每个键最多只能映射到一个值
5.Map接口提供了分别返回key值集合,value值集合以及Entry(键值对)集合的方法
6.Map支持泛型,形式如:Map<K,V>


HashMap类

  • HashMap是Map的一个重要实现类,也是最常用的,基于哈希表实现的类。

方法:

代码示例:

containsKey和containsValue

  • 1、Map中分别通过containsKey()方法和containsValue()方法判断映射表中是否包含特定的key值和Value值,通过equals()方法遍历映射表中的每一个Key和Value
public class MapContains {
    HashMap<Integer,Student> studentMap=new HashMap<Integer, Student>();
    public void testAdd() {
//创建若干学生对象以供测试
        Student student1=new Student("小红");
        Student student2=new Student("小明");
        Student student3=new Student( "小张");

         studentMap.put(1,student1);
         studentMap.put(2,student2);
         studentMap.put(3,student3);
    }
        public void testContains(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入学生名字name");
        String name=scanner.next();
        Student student=new Student(name);
        if(studentMap.containsValue(student)){
            System.out.println("含有"+"学生"+student.name);
            System.out.println("测试成功");
        }
            }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    MapContains mapContains=new MapContains();
    mapContains.testAdd();
    mapContains.testContains();

    }
}

输出结果:

上一篇 下一篇

猜你喜欢

热点阅读