Advertisement
Guest User

Untitled

a guest
Jul 24th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Set;
  3. import java.util.HashSet;
  4. public class HashCodeForString{
  5. public static void main(String[] args) {
  6. // Create a hash set
  7. Set<String> set = new HashSet<>();
  8.  
  9. // Add strings to the set
  10. set.add("CIS 315");
  11. set.add("Java");
  12. set.add("Programming");
  13. set.add("Justin Clark");
  14.  
  15. ArrayList<String> myArrayList = setToList(set);
  16.  
  17. // Display the hash code for each element in the array list
  18. for (String str : set) {
  19. System.out.println("The hash code for \"" + str + "\" = "+ hashCodeForString(str));
  20. }
  21. }
  22.  
  23. // Return a hash code for a string
  24. public static int hashCodeForString(String s) {
  25. int myhash = 0;
  26. for (int i = 0; i < s.length(); i++){
  27. myhash += s.charAt(i) * Math.pow(31,(s.length() - (i + 1)));
  28. }
  29. return myhash;
  30. }
  31.  
  32. // Return an ArrayList from a set
  33. public static <E> ArrayList<E> setToList(Set<E> s) {
  34. ArrayList<E> mylist = new ArrayList<E>();
  35. for(E i : s)
  36. mylist.add((E) i);
  37. return mylist;
  38. }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement