在Java的ArrayList的ArrayList中使用[]。

huangapple go评论80阅读模式
英文:

Use [] in ArrayList of ArrayLists java

问题

我正在创建一个哈希表,它是ArrayList<ArrayList<Integer>> Table = new ArrayList<ArrayList<Integer>>(size);
我想要检查哈希码为n的槽是否为空,使用if(Table[n] == null) 但这是错误的。这有什么问题?

英文:

I'm creating a hashtable that is a ArrayList&lt;ArrayList&lt;Integer&gt;&gt; Table = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(size);
I want to check if the slot with hash code n is null, using if(Table [n] == null) but ths is wrong. What's wrong with it?

答案1

得分: 3

你不能使用[...]的语法访问ArrayList的元素,这只适用于数组。请使用以下方式:

if(Table.get(n) == null)

作为一个无关的注意事项,养成遵循Java命名约定的习惯。变量名应以小写字母开头。

英文:

You cannot access the elements of an ArrayList with the [...] syntax. That is only available for arrays. Use

if(Table.get(n) == null)

instead.

As an unrelated note, make it a habit to follow the Java naming conventions. Variable names should start with a lower case letter.

答案2

得分: 0

基本上,哈希表的工作原理如下以插入项为例(可能会有所不同):

int hash = obj.hashCode();
table[hash % table.length].push(obj);

你必须为表格指定一个确定的长度,以便能够正确地工作,并且能够在任何给定的时间访问数组中的所有位置。当然,ArrayList 可以模仿这种行为,但它只会使其变慢,在幕后,它实际上只是一个普通的数组。

英文:

Fundamentally a hashtable works as follows to insert an item (give or take):

int hash = obj.hashCode();
table[hash % table.length].push(obj);

You must have a definite length for the table to work correctly and be able to access all positions in the array at any given time. Sure an ArrayList can mimic this behavior, but it just makes it slower and under the hood its just a plain old array anyway.

huangapple
  • 本文由 发表于 2020年10月8日 11:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64255231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定