tags:

views:

45

answers:

3

I have this hashCode function that I have been trying to implement with Eclipse but my Tests keep failing. I am trying to write a Hashcode function that returns that last 2 or 3 chars of a word or number. Here is my current code:

 public int hashCode(String value){
 String test = value;
 int hash = 1;
 int len = test.length();
 System.out.println(len);
 for ( int i=0; i<len; i++ )
       {
       hash = 31 * hash + len;
       }
    return hash;
}

Here is my Junit Test:

    @Test // hashCode()
 public void testHashCode1() {
  //Integer key1 = 123;
  String key2 = "and";
  assertEquals("and", key2.hashCode());
 }

Everytime I run my test it fails indicating:

expected but was: <96727>

Now I really would like for this function to take in either a Word or Number and return the last two or three chars of the object taken in. Does anyone know how to do this using hashCode. Any help would be most appreciated

A: 

It may be a problem with the editor mangling the code, but I do not see value or test used anywhere inside the loop.

James Curran
but I have len = test.length() and len is part of hash = 31 * hash + len;
@alpdog but those values won't change for each iteration of the loop, so you'll get the same value for all strings of the same length
Rowland Shaw
Should I change my method to something like:public int hashCode() { // inside the String is a char[] val that holds the characters. int hash = 0; int len = char.length(); for ( int i=0; i<len; i++ ) { hash = 31 * hash + val[ i ]; } return hash; }
A: 

public int hashCode(String value)

and calling as

assertEquals("and", key2.hashCode());

you are not even overriding it properly change the signature to take no arguments please :)

Calm Storm
Also hashCode returns an integer and do not compare it with a String :)
Calm Storm
Should I change my method to something like: public int hashCode() { // inside the String is a char[] val that holds the characters. int hash = 0; int len = char.length(); for ( int i=0; i<len; i++ ) { hash = 31 * hash + val[ i ]; } return hash; }
i do not know how to break lines
A: 

Should I change the code to something similar to this:

public int hashCode()
   {
   // inside the String is a char[] val that holds the characters.
   int hash = 0;
   int len = char.length();
   for ( int i=0; i<len; i++ )
      {
      hash = 31 * hash + val[ i ];
      }
   return hash;
   }