简体   繁体   English

哈希图中put方法的实现

[英]implementation of put method in a hashmap

I was reading about maps in java. 我正在阅读有关Java中的地图的信息。 I did this code. 我做了这段代码。

public class Test {

    private HashMap<String, Integer> h;
    private int dataCount;

    public Test() {

        h = new HashMap<String, Integer>();
        dataCount = 0;
    }

    public String getNumber(String name) {

        for (String k : h.keySet()) {
            if (k.equals(name)) {
                Integer v = h.get(k);
                return k+" "+v;
            }
        }
        return null;
    }

    public void putNumber(String name, Integer number) {
        Iterator<String> i = h.keySet().iterator();
        if (i.equals(name)) {
            h.put(name, number);
        } 
        h.put(name, number);
        dataCount++;

    }

//  public void putNumber(String name, Integer number) {
//      
//      for (String k : h.keySet()) {
//          if(k.equals(name)) {
//              h.put(k, number);
//          } 
//              h.put(name, number);
//              dataCount++;
//          }
//  }


    public static void main(String[] args) {

        Test t = new Test();
        t.putNumber("ali", 123);
        t.putNumber("ala", 658);
        t.putNumber("baba", 987);
        t.putNumber("ali", 666);

        System.out.println(t.dataCount);
        System.out.println(t.getNumber("ali"));
        System.out.println(t.h);

    }

}

When I run this code I get : 当我运行此代码时,我得到:

4
ali 666
{baba=987, ala=658, ali=666}

It should not be like that, I want it to be like this : 它不应该是这样,我希望它是这样的:

3
{ali 666, baba=987, ala=658}

in my putNumber method when a name is already exisitng in the map so I just want to change its number and not add the same name again with a new number. 在地图中已经存在名称的情况下,在我的putNumber方法中,因此我只想更改其编号,而不是使用新编号再次添加相同的名称。

I have also that my second putNumber method with the for each loop does not nork at all. 我也有我的第二个putNumber方法与for每个循环根本不规范。 When I run the code with the putNumber method (for each one) I get this: 当我使用putNumber方法运行代码时(针对每个方法),我得到以下信息:

0
null
{}

Thanks 谢谢

Your putNumber method contains multiple errors : 您的putNumber方法包含多个错误:

  • i.equals(name) you're comparing a String with an Iterator<String> . i.equals(name)您正在将StringIterator<String>进行比较。 That won't work 那行不通
  • if your condition was ever true, you would execute h.put twice (which isn't problematic, but clearly is useless) 如果您的条件为真,则将执行两次h.put (这没有问题,但显然没有用)
  • you would always execute dataCount++ (when it should be the only thing conditioned) 您将始终执行dataCount++ (当它应该是唯一的条件时)

Here's what I would do instead : 这是我要做的:

public void putNumber(String name, Integer number) {
    if (!h.containsKey(name)) {
        dataCount++;
    }
    h.put(name, number);
}

Alternatively, using an HashTable (where null isn't an authorized value) instead of an HashMap would make it possible to rely on the return value of HashTable.put(key, value) which will return null if there was no previous mapping for the key : 另外,如果使用HashTable (其中的null不是授权值)代替HashMap ,则可以依赖HashTable.put(key, value)返回null如果该映射没有先前的映射,则将返回nullkey

public void putNumber(String name, Integer number) {
    if (h.put(name, number) == null) {
        dataCount++;
    }
}

Also note that the HashMap class defines a .size() method which might make maintaining a dataCount variable useless. 还要注意, HashMap类定义了.size()方法,这可能会使维护dataCount变量无用。

I think your putNumber method is wrong, it should be something like 我认为您的putNumber方法是错误的,应该是这样的

public void putNumber(String name, Integer number) {
    Iterator<String> i = h.keySet().iterator();
    if (i.equals(name)) {
        h.put(name, number);
    } else {
        h.put(name, number);
        dataCount++;
    }
}

Right now, if the key is already present, it will still increase the dataCount . 现在,如果密钥已经存在,它将仍然增加dataCount

However, there's another problem with this code. 但是,此代码还有另一个问题。 One of the main advantages of using a HashMap is that you can look up the keys very fast; 使用HashMap的主要优点之一是您可以非常快速地查找密钥。 you don't need to iterate over the keyset, you can just use h.containsKey(name) and h.get(name) . 不需要遍历键集,只需使用h.containsKey(name)h.get(name) Also, it has a built-in size() method with the same properties as your dataCount . 此外,它具有内置的size()方法,该方法具有与dataCount相同的属性。

You are not using HashMap correctly. 您没有正确使用HashMap

There's no point in iterating over the keySet to locate a specific key. 遍历keySet以定位特定键没有意义。 That's what get , put and containsKey are for. 这就是getputcontainsKey的用途。

public void putNumber(String name, Integer number) { 
    if (h.put(name, number) == null)
        dataCount++; // increment the counter only if the name was not already in the Map
}

public String getNumber(String name) {
    Integer v = h.get(name);
    return v == null ? null : name+" "+v;
}
public void putNumber(String name, Integer number) {
    Iterator<String> i = h.keySet().iterator();
    if (i.equals(name)) {
        h.put(name, number);
    } 
    h.put(name, number);
    dataCount++;
}

1) In any cases, you put the element in the map. 1)在任何情况下,您都将元素放在地图中。 So you should not repeat yourself. 因此,您不应该重复自己。
2) Besides dataCount is incremented at each time even when no new value is added. 2)此外,即使没有添加新值,dataCount也会每次增加。
3) if (i.equals(name)) doesn't compare all keys but compare the iterator value with the name parameter. 3) if (i.equals(name))不比较所有键,而是将迭代器值与name参数进行比较。

Try that : 尝试:

public void putNumber(String name, Integer number) {
     if (!h.containsKey(name)){
         dataCount++;    
     }
     h.put(name, number);               
 } 

Besides, getNumber() could be also simplify since by using one more time the containsKey() method of the map. 此外,由于还多使用了地图的containsKey()方法,因此getNumber()也可以得到简化。

public String getNumber(String name) {     
     if (h.containsKey(name)){
         Integer v = h.get(k);
         return k+" "+v;    
     }               
    return null;
}

Your putNumber method makes little sense: 您的putNumber方法毫无意义:

public void putNumber(String name, Integer number) {
    Iterator<String> i = h.keySet().iterator(); //i is an iterator
    //this returns always false, you are comparing an iterator to a string
    if (i.equals(name)) {
        h.put(name, number);
    }

    //this code is always executed
    h.put(name, number);
    dataCount++;
}

What you should do is something like: 您应该执行的操作如下:

public void putNumber(String name, Integer n) {
    h.put(name,n);
    dataCount=h.size();
}

Or, if you want something more "manual": 或者,如果您想要更多“手动”功能:

public void putNumber(String name, Integer n) {
    if (h.get(name)==null) {
        dataCount++;
    }
    h.put(name,n);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM