简体   繁体   English

关于Java HashMap源

[英]About Java HashMap sources

So, we have a HashMap, and a transient Entry[] table inside it. 因此,我们有一个HashMap和一个临时的Entry []表。 In many methods, for example, in clear(), we copy table: 在许多方法中,例如在clear()中,我们复制表:

public void clear() {
    modCount++;
    Entry[] tab = table;
    for (int i = 0; i < tab.length; i++)
        tab[i] = null;
    size = 0;
}

But why we do Entry[] tab = table? 但是为什么我们要使用Entry [] tab = table? What's wrong in next code? 下一个代码有什么问题?

public void clear() {
    modCount++;
    for (int i = 0; i < table.length; i++)
        table[i] = null;
    size = 0;
}

As far as i know, tab is only a reference to table, and, for at first sight, is just a wasting of space. 据我所知,制表符只是对表的引用,乍一看,只是浪费了空间。

 for (int i = 0; i < table.length; i++)
        tab[i] = null;

You are right, tab and table both point to the same object. 是的, tabtable都指向同一对象。 The problem I see is using table in the for-conditional and tab in the for-body. 我看到的问题是在for-condition中使用table,在for-body中使用tab。 You should use one or the other, but not both. 您应该使用其中一个,但不能同时使用两者。

tab is unnecessary, but sometimes people do this for readability reasons. tab是不必要的,但有时出于可读性原因人们这样做。 Doesn't make sense here, since table is more readable. 在这里没有意义,因为表格更具可读性。 If I were code reviewing this, I would strongly prefer the second version. 如果我正在代码审查此,我强烈希望第二个版本。

It's just one locally scoped object reference. 这只是一个本地范围内的对象引用。 Not a lot of space there. 那里没有很多空间。

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

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