英文:
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<ArrayList<Integer>> Table = new ArrayList<ArrayList<Integer>>(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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论