Java教程

Map接口,个人学习

本文主要是介绍Map接口,个人学习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Map接口的注意点

  • Map是一种把键对象和值对象进行关联的容器,而一个值对象又可以是一个Map,依次类推,这样就可形成一个多级映射
  • 键对象不允许重复!Map没有继承Collection接口!一个Map中不能包含相同的key,每个key只能映射一个value
  • Map接口提供3种集合,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射
可以理解为key相当于“学号”,value相当于对应的“姓名”,“姓名”之后对应的“年龄”依次类推。

常用方法:(实现类常用HashMap)

  • put(k,v)
HashMap map = new HashMap();
        map.put( "罗","20" );
  • get(k)
HashMap map = new HashMap();
        map.put( "罗","20" );
        System.out.println( map.get( "罗" ) );
  • remove(k)
HashMap map = new HashMap();
        map.put( "罗","20" );
        map.remove("罗");
  • containskey(k)
 HashMap map = new HashMap();
        map.put( "罗","20" );
        System.out.println( map.containskey("罗"));
  • containsvalue(v)
HashMap map = new HashMap();
        map.put( "罗","20" );
        System.out.println( map.containsvalue("20") )
  • isEmpty()
HashMap map = new HashMap();
        map.put( "罗","20" );
        System.out.println(map.isEmpty())
  • 等等~~
public static void main(String[] args) {
        Map map = new HashMap();
        map.put( "001","罗同学" );
        map.put( "002","李同学" );
        map.put( "003","莫同学" );
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        System.out.println("key元素中的元素:");
        while (iterator.hasNext()){
            System.out.println( iterator.next() );
        }
        Collection coll = map.values();
        iterator = coll.iterator();
        System.out.println("value集合中的元素:");
        while (iterator.hasNext()){
            System.out.println( iterator.next() );
        }
    }
public static void main(String[] args) {
        Map map = new HashMap();
        Emp emp1 = new Emp( "001","罗焕钊" );
        Emp emp2 = new Emp( "003","小钊" );
        Emp emp3 = new Emp( "005","小罗" );
        Emp emp4 = new Emp( "006","小焕" );
        Emp emp5 = new Emp( "008","小焕钊" );

        map.put( emp1.getE_id(),emp1.getE_name() );
        map.put( emp2.getE_id(),emp2.getE_name() );
        map.put( emp3.getE_id(),emp3.getE_name() );
        map.put( emp4.getE_id(),emp4.getE_name() );
        map.put( emp5.getE_id(),emp5.getE_name() );

        Set set = map.keySet();
        Iterator it = set.iterator();
        System.out.println("HashMap实现的集合:");
        while (it.hasNext()){
            String str = (String) it.next();
            String name = (String) map.get( str );
            System.out.println(str+"  "+name);
        }
        TreeMap treeMap = new TreeMap();
        treeMap.putAll( map );
        Set set1 = treeMap.keySet();
        Iterator it1 = set.iterator();
        System.out.println("treemap实现的集合:");
        while (it1.hasNext()){
            String str1 = (String) it1.next();
            String name1 = (String) treeMap.get( str1 );
            System.out.println(str1+"  "+name1);
        }
    }
这篇关于Map接口,个人学习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!