Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Set;
- import java.util.HashSet;
- public class HashCodeForString{
- public static void main(String[] args) {
- // Create a hash set
- Set<String> set = new HashSet<>();
- // Add strings to the set
- set.add("CIS 315");
- set.add("Java");
- set.add("Programming");
- set.add("Justin Clark");
- ArrayList<String> myArrayList = setToList(set);
- // Display the hash code for each element in the array list
- for (String str : set) {
- System.out.println("The hash code for \"" + str + "\" = "+ hashCodeForString(str));
- }
- }
- // Return a hash code for a string
- public static int hashCodeForString(String s) {
- int myhash = 0;
- for (int i = 0; i < s.length(); i++){
- myhash += s.charAt(i) * Math.pow(31,(s.length() - (i + 1)));
- }
- return myhash;
- }
- // Return an ArrayList from a set
- public static <E> ArrayList<E> setToList(Set<E> s) {
- ArrayList<E> mylist = new ArrayList<E>();
- for(E i : s)
- mylist.add((E) i);
- return mylist;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement