1

I am trying to create a method that counts how many collision occur in a hash table. Would I check the entire table to see how many buckets have more than 1 element?

Draft:

 public int getCollisions() { int counter = 0; for (int i = 0; i < buckets.length; i++) { if (buckets.length > 1) { counter += i; } } return counter; } 
5
  • 2
    Yes. That is what I would do. Actually, you would increment a counter with every bucket length greater then 1. So, if (bucket.length > 1) { counter += bucket.length; } Commented Dec 6, 2013 at 21:02
  • Would it be alright for me to propose a draft method for you to check @Elliott Frisch? Commented Dec 6, 2013 at 21:06
  • The draft method is not adding the number of collisions, rather the index of the bucket. Commented Dec 6, 2013 at 21:12
  • Would it be buckets.length then, similar to Elliot's post? Commented Dec 6, 2013 at 21:15
  • See my answer (specifically the bit after the code), but basically yes, and you also had a faulty if statement condition. Commented Dec 6, 2013 at 21:20

2 Answers 2

2

I would probably use this -

public long getCollisions() { long counter = 0; for (int i = 0; i < buckets.length; i++) { if (buckets[i].length > 1) { counter += buckets[i].length; // 2 (or more) items collided in this bucket. } } return counter; } 
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason I am not able to do buckets[i].length, shouldn't length be a default method?
1

You are adding the index of the bucket, not the number of collisions to your counter. Try this instead:

public int getCollisions() { int counter = 0; for (int i = 0; i < buckets.length; i++) { if (buckets[i].length > 1) { counter += buckets[i].length-1; } } return counter; } 

Here I am assuming that if there are n objects in a bucket (where n>1), there are n-1 collisions in that bucket. If I am incorrect in assuming that, then just remove the -1 and it should work fine.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.