zoukankan      html  css  js  c++  java
  • Vector Dictionary HashMap

    集合中只能够存储对象。

    所有集合容纳的只有对象句柄。

    vector:通过索引找到对应的对象,线性搜索

    dictionary:通过对象(键)找到相应的对象(值)

    Dictioary类实现的方法:使用两个Vector类

    实现一个dictionary类

    import java.util.Dictionary;
    import java.util.Enumeration;
    import java.util.Vector;

    public class myDictionary extends Dictionary{


    private Vector keys=new Vector();
    private Vector values=new Vector();

    public int size() {
    return keys.size();
    }


    @Override
    public boolean isEmpty() {

    return keys.isEmpty();
    }


    @Override
    public Enumeration keys() {
    return keys.elements();
    }


    @Override
    public Enumeration elements() {
    return values.elements();
    }


    @Override
    public Object get(Object key) {
    int num=keys.indexOf(key);
    if(num==-1){
    return null;
    }
    return values.elementAt(num);
    }


    @Override
    public Object put(Object key, Object value) {
           keys.addElement(key);
           values.addElement(value);
    return null;
    }


    @Override
    public Object remove(Object key) {
    int index=keys.indexOf(key);
    if(index==-1) return null;
    keys.removeElementAt(index);
    Object o=values.elementAt(index);
    values.removeElementAt(index);
    return o;
    }
    }

    HashTable(散列表) 是dictionary的一个变种,查找速度快,通过散列码查找。所有对象都有一个散列码,hashCode()是跟雷的一个方法,Hashtable通过获取对象的hashCode,然后用他快速查找键。

    HashTable ht=new HashTable();

    ht.put( new test1(), new test2());

    //键值对是自己定义的类,会出现问题,要在作为键的类中覆盖hashCode()和equals()方法。

    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Hashtable;
    class test1{
    int num;
    test1(int i){
    num=i;
    }
    public int hashCode(){
    return num;
    }
    public boolean equals(Object o){
    if(o!=null && o instanceof test1)//instanceof关键字:是否为test1的一个实例
    {
    return num== ((test1)o).num;
    }
    else return false;
    }
    }
    class test2{
    boolean shadow=Math.random()>0.5;
    public String toString(){
    if(shadow){
    return "six";
    }else{
    return "five";
    }
    }
    }
    public class Test {
      public static void main(String [ ]args){
    Hashtable ht=new Hashtable();
    for(int i=0;i<10;i++){
    ht.put(new test1(i),new test2());
    }
     test1 test11=new test1(3);
     System.out.println(test11.hashCode());
     if(ht.containsKey(test11)){
     System.out.println((test2)ht.get(test11));
     }
      }
    }




  • 相关阅读:
    Codeforces Global Round 11 E Xum
    【NFLSPC #2】Polynomial
    【SHOI2015】脑洞治疗仪 题解 (线段树)
    CDQ分治与整体二分 学习笔记
    二维树状数组 学习笔记
    博弈论 学习笔记
    【JSOI2007】文本生成器 题解(AC自动机+动态规划)
    【NOI2018】归程 题解(kruskal重构树+最短路)
    【NOI2017】游戏 题解(2-SAT+缩点)
    【BZOJ4398】福慧双修 题解(建图优化)
  • 原文地址:https://www.cnblogs.com/yeemi/p/7470193.html
Copyright © 2011-2022 走看看