I have a problem with adding String to a ArrayList>. Which is declared
ArrayList<LinkedList<String>> table = new ArrayList<>();
In the constructor of the class I call ArrayLists ensureCapacity method, which doesn't seem to do what I was expecting. I was thinking it would increase the slots for LinkedList inside it, but it just remains empty.
When I try to call my add method:
public boolean add(String s)
{
boolean wanted = true;
if(false)
{
wanted = false;
}
int index = Math.abs(s.hashCode() % table.size());
table.ensureCapacity(index);
table.get(index).addFirst(s);
return wanted;
}
Since the table size doesn't get increased by ensureCapacity, I get java.lang.ArithmeticException: by zero. How can I work around this? I pictured this in my head as the ArrayList being the first column in a table, and LinkedLists being the rows. So each slot in the ArrayList references a LinkedList which Strings would be saved in. But since the ArrayList is empty at start and I can't increase with ensureCapacity and using the % operator in the add method it won't increase itself.
table.size()is 0 and giving you the exception your seeing. Maybe put a check that saysif(table.size() == 0) { /*increase table size*/ }