Advertisement
Guest User

Untitled

a guest
Jul 24th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import java.math.BigInteger;
  2. import java.util.ArrayList;
  3. import java.util.Set;
  4. import java.util.HashSet;
  5. public class HashCodeForString{
  6. public static void main(String[] args) {
  7. // Create a hash set
  8. Set<String> set = new HashSet<>();
  9.  
  10.  
  11.  
  12. // Add strings to the set
  13. // set.add("az");
  14. // set.add("Java");
  15. // set.add("Programming");
  16. set.add("Justin Clark");
  17.  
  18.  
  19. //ArrayList<String> myArrayList = setToList(set);
  20.  
  21. // Display the hash code for each element in the array list
  22. for (String str : set) {
  23. System.out.println("The hash code for \"" + str + "\" = "+ hashCodeForString(str));
  24. }
  25. }
  26.  
  27. // Return a hash code for a string
  28. public static int hashCodeForString(String s) {
  29. int myhash = 0;
  30.  
  31. //Algorithm: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
  32. for (int i = 0; i < s.length(); i++){
  33. int n = s.length() - (i + 1);
  34. BigInteger exp = BigInteger.valueOf(31);
  35. exp = exp.pow(n);
  36.  
  37.  
  38. myhash += (exp.multiply(BigInteger.valueOf(s.charAt(i))).intValue());
  39. }
  40. int realHash = s.hashCode();
  41. return myhash;
  42. }
  43.  
  44. public static int testHashCode(String s) {
  45. //Modified hash version found online.
  46. //Supposedly the version java uses internally for String objects
  47. //Found at http://java-bytes.blogspot.com/2009/10/hashcode-of-string-in-java.html
  48. int h = 0;
  49.  
  50. for (int i = 0; i < s.length(); i++) {
  51. h = 31*h + s.charAt(i);
  52. }
  53.  
  54. return h;
  55. }
  56.  
  57. // Return an ArrayList from a set
  58. public static <E> ArrayList<E> setToList(Set<E> s) {
  59. ArrayList<E> mylist = new ArrayList<E>();
  60. for(E i : s)
  61. mylist.add((E) i);
  62. return mylist;
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement