OnJava8-Examples/equalshashcode/CountedString.java

70 lines
2.0 KiB
Java
Raw Permalink Normal View History

2017-01-10 14:11:16 -08:00
// equalshashcode/CountedString.java
// (c)2021 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
// of this String used by CountedString:
2015-06-15 17:47:35 -07:00
for(String s2 : created)
if(s2.equals(s))
id++;
}
@Override public String toString() {
2015-06-15 17:47:35 -07:00
return "String: " + s + " id: " + id +
" hashCode(): " + hashCode();
}
@Override public int hashCode() {
2015-06-15 17:47:35 -07:00
// 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) {
2015-06-15 17:47:35 -07:00
return o instanceof CountedString &&
2017-01-08 22:55:49 -08:00
Objects.equals(s, ((CountedString)o).s) &&
Objects.equals(id, ((CountedString)o).id);
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
2017-01-10 14:11:16 -08:00
Map<CountedString,Integer> map = new HashMap<>();
2015-06-15 17:47:35 -07:00
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:
{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}
2015-06-15 17:47:35 -07:00
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
*/