简体   繁体   English

在ArrayLists的ArrayList中使用[] java

[英]Use [] in ArrayList of ArrayLists java

I'm creating a hashtable that is a ArrayList<ArrayList<Integer>> Table = new ArrayList<ArrayList<Integer>>(size);我正在创建一个哈希表,它是一个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.我想使用if(Table [n] == null)检查哈希代码 n 的插槽是否为空,但这是错误的。 What's wrong with it?它出什么问题了?

You cannot access the elements of an ArrayList with the [...] syntax.您不能使用[...]语法访问 ArrayList 的元素。 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.作为一个无关的说明,请养成遵循 Java 命名约定的习惯。 Variable names should start with a lower case letter.变量名应以小写字母开头。

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.当然ArrayList可以模仿这种行为,但它只会让它变慢,而且无论如何它只是一个普通的旧数组。

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

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