0

I'm writing a hash table code. Taking mode according to table size.I want to start with table -1 and null.I understand that it is empty. Java hash table ready.So I do not find many examples.

My fill_in method is not running.

class Node{

int index;
int number;
Node next;

public Node(int index,int number,Node next){
    this.index=index;
    this.next=next;
    this.number=number;
}

}

class Table{
int max_row;

public Table(int size){
    this.max_row=size;
}

Node rows[]= new Node[max_row];

public void fill_in(){

    for(int i=0; i<max_row;i++)
        rows[i]=new Node(-1,-1,null);
}
mrsengineer
  • 27
  • 2
  • 8
  • "not running" or "not compile" ? – Jacek Cz Jan 16 '17 at 19:49
  • ArrayIndexOutOfBoundsException – mrsengineer Jan 16 '17 at 19:50
  • What's your size? And your input example? – Frakcool Jan 16 '17 at 19:51
  • 1
    @Tunaki this isn't a duplicate to your link, his error is directly due to the fact he tries to initialize his array before max_row has been initialized and that's why he gets the error when trying to fill it. – RAZ_Muh_Taz Jan 16 '17 at 20:02
  • @RAZ I disagree, their problem is an `ArrayIndexOutOfBoundsException`, which has a single cause explained in the linked question. The actual steps to resolve the issue _might_ differ, but truly understanding the problem is far more helpful, and always leads to the solution. The OP doesn't know what the exception means, so redirecting to the canonical is the best way to help them. – Tunaki Jan 16 '17 at 20:07
  • @Tunaki His current implementation always creates an array of Nodes with size 0 and because of the incorrect class construction he runs into the array index out of bounds exception. If he fixes the class construction he won't run into the array out of bounds exception. The problem is more than just an index out of bounds exception – RAZ_Muh_Taz Jan 16 '17 at 20:14

2 Answers2

0

You should initialize your array in constructor, because now it is initialized with unknown max_row.

class Table {
    int max_row;
    Node rows[];

    public Table(int size) {
        this.max_row = size;
        rows = new Node[max_row];
}
0

You are trying to set the size of your Node array to the size of the value in max_size before it has been initialized. Change your class to this

class Table{
    int max_row;
    Node rows[];

public Table(int size){
    max_row = size;
    rows = new Node[max_row];
}

public void fill_in(){

    for(int i=0; i<max_row;i++)
        rows[i]=new Node(-1,-1,null);
}
}
RAZ_Muh_Taz
  • 4,059
  • 1
  • 13
  • 26