zoukankan      html  css  js  c++  java
  • Map集合

    Map接口主要实现类有HashMap,HashTable,TreeMap.

    键要唯一,值可以一样,若是键一致,后面存入的会覆盖前面的。

    HashMap,HashTable区别:HashMap可以键值都可以是null,线程是不同步的;而HashTable的键值都不可以为null,线程是同步的。

    Hash比较唯一性是hashCode();equals()方法;map有两种迭代取出,entrySet(),keySet.

    entrySet()返回的是Set<Map.entry<K,V>>,存到set中的是KEY 和Value的对应关系。通过迭代器取出;取出的方法是getkey(),getValue();

    keySet返回的是Key的Set集合;再通过get(key),返回值。

    而TreeMap要键元素自身具有比较性,Comparable接口和comparaTo方法。或者集合有Comparator接口的compare方法。

    public class HashMapTest {
    public static void main(String[] args){
    HashMap<Student,String> ha = new HashMap<Student,String>();

    ha.put(new Student("lisi",23), "tianjing");
    ha.put(new Student("wangwu",23), "beijian");
    ha.put(new Student("zhaoliu",23), "nanjing");
    ha.put(new Student("lisi",23), "shanghai");

    /*
    * 方式一:keySet
    * */
    /*
    Set<Student> keySet = ha.keySet();
    Iterator<Student> it = keySet.iterator();
    while(it.hasNext()){
    Student stu = it.next();
    String add = ha.get(stu);
    System.out.println("stu:"+stu.getName()+"---stu_add--"+add);
    }
    */

    /*
    * 方式2:entrySet
    * */
    Set<Map.Entry<Student, String>> entry = ha.entrySet();
    Iterator<Map.Entry<Student, String>> it = entry.iterator();
    while(it.hasNext()){
    Map.Entry<Student, String> entry1 = it.next();
    System.out.println("---Key--"+entry1.getKey().getName()+"---value---"+entry1.getValue());
    }
    }
    }

    class Student{
    private String name;
    private int age;

    public Student(String name, int age) {
    super();
    this.name = name;
    this.age = age;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public int hashCode(){
    System.out.println("调用hashcode--------");
    return age;
    }
    public boolean equals(Object obj){
    if(!(obj instanceof Student)){
    throw new ClassCastException("不是学生类型");
    }
    System.out.println("调用equals----------");
    Student stu = (Student)obj;
    return this.name.equals(stu.getName());
    }
    }

  • 相关阅读:
    sql datepart ,dateadd,datediff,DateName函数
    DEV控件:gridControl常用属性设置
    师兄建议:
    .GRIDVIEW奇偶行变色
    C#中在主窗体中用ShowDialog方法显示子窗体的使用技巧
    Dev 控件lookUpEdit的数据绑定及其获取从UI界面赋给lookupedit的值
    从VS界面把图片导入数据库:①:把图片转换为二进制数据,②再把二进制数存进数据库
    YYKit之YYText
    分享使用method swizzling的经历
    autoreleasepool的笔记
  • 原文地址:https://www.cnblogs.com/daxiong225/p/4593175.html
Copyright © 2011-2022 走看看