2016-08-02 11:52:46 -06:00
|
|
|
// understandingcollections/CountedString.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Creating a good hashCode()
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class CountedString {
|
|
|
|
private static List<String> created =
|
|
|
|
new ArrayList<>();
|
|
|
|
private String s;
|
|
|
|
private int id = 0;
|
|
|
|
public CountedString(String str) {
|
|
|
|
s = str;
|
|
|
|
created.add(s);
|
|
|
|
// id is the total number of instances
|
2015-11-11 20:20:04 -08:00
|
|
|
// of this String in use by CountedString:
|
2015-06-15 17:47:35 -07:00
|
|
|
for(String s2 : created)
|
|
|
|
if(s2.equals(s))
|
|
|
|
id++;
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
return "String: " + s + " id: " + id +
|
|
|
|
" hashCode(): " + hashCode();
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public int hashCode() {
|
|
|
|
// The very simple approach:
|
|
|
|
// return s.hashCode() * id;
|
|
|
|
// Using Joshua Bloch's recipe:
|
|
|
|
int result = 17;
|
|
|
|
result = 37 * result + s.hashCode();
|
|
|
|
result = 37 * result + id;
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public boolean equals(Object o) {
|
|
|
|
return o instanceof CountedString &&
|
|
|
|
s.equals(((CountedString)o).s) &&
|
|
|
|
id == ((CountedString)o).id;
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Map<CountedString,Integer> map =
|
|
|
|
new HashMap<>();
|
|
|
|
CountedString[] cs = new CountedString[5];
|
|
|
|
for(int i = 0; i < cs.length; i++) {
|
|
|
|
cs[i] = new CountedString("hi");
|
|
|
|
map.put(cs[i], i); // Autobox int to Integer
|
|
|
|
}
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(map);
|
2015-06-15 17:47:35 -07:00
|
|
|
for(CountedString cstring : cs) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Looking up " + cstring);
|
|
|
|
System.out.println(map.get(cstring));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
{String: hi id: 4 hashCode(): 146450=3, String: hi id: 5
|
|
|
|
hashCode(): 146451=4, String: hi id: 2 hashCode():
|
|
|
|
146448=1, String: hi id: 3 hashCode(): 146449=2, String: hi
|
|
|
|
id: 1 hashCode(): 146447=0}
|
|
|
|
Looking up String: hi id: 1 hashCode(): 146447
|
|
|
|
0
|
|
|
|
Looking up String: hi id: 2 hashCode(): 146448
|
|
|
|
1
|
|
|
|
Looking up String: hi id: 3 hashCode(): 146449
|
|
|
|
2
|
|
|
|
Looking up String: hi id: 4 hashCode(): 146450
|
|
|
|
3
|
|
|
|
Looking up String: hi id: 5 hashCode(): 146451
|
|
|
|
4
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|