0

I am new to Java. I can't figure out how to do this without pointers:

// hash table with seperate chaining

class HashTbl {
  class Node {
    int data;
    Node next;
  }

  private Node tbl[];

  HashTbl(int size) {
    tbl[] = new Node[size * 1.25];
  }

  public int insert(int item) {
    // insert data
  }

  public Node lookup(int item) {
    // search for item in the hashtable
    // the item was found at array index 'idx'
    return tbl[idx];
  } 

  public int remove (int item) {
    Node n = lookup(item);
    n = null;  // <--- this obviously doesn't work, what i want to do is set tbl[idx] to null
  }

}

Setting the local reference variable to null doesn't affect the actual array. In c++ i would return a pointer to the array element so that i can set the array element to Null via the pointer. Now, there are no pointers in Java, so how can i make this work?

Update: returning an the array index or using a separate function that returns a the matched index are 2 possible workarounds. But i am not just looking for a solution to this particular program. What about this problem in general?

2
  • Java doesn't have pointers, but you can pass in an array and an index together, and clear out that slot in the array. Commented Apr 24, 2011 at 18:10
  • Chris, i think i will go with your solution :-) Commented Apr 29, 2011 at 19:16

4 Answers 4

1

Simply do this:

tbl[item] = null;

Update: I missed the fact that there is some omitted code in lookup(). Do this instead:

private int findIdx(int item) {
  // search for item in the hashtable
  // the item was found at array index 'idx'
  return idx;
} 

public Node lookup(int item) {
  return tbl[findIdx(item)];
}   

public int remove (int item) {
  tbl[findIdx(item)] = null;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think he intentionally omitted the irrelevant way of finding out idx in the lookup method. I believe that generally idx != item.
Yeap, item should match the data field in the Node object.
1

Simplest way: have lookup return idx and use that in remove. Alternatively, if you need the lookup method to be public in that form, make a new, private method that returns the index.

Comments

1
public int lookup(int item) {
  // search item in hash, return index
  return idx;
} 

public int remove (int item) {
  int idx = lookup(item);
  tbl[idx] = null;
}

Comments

0

I would suggest you use ArrayList other than common array.

List<Node> tbl = new ArrayList<Node>();

look up the java manual for detail.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.