| HashMap log-debugged |
|
|
|
| Written by Charles | |||||
| Thursday, 08 July 2010 22:03 | |||||
|
The link below is to a version of Java's HashMap class with logback logging made initially for educational purposes, although this could be used during testing code to examine the Map internals.
<logger name="l_hashing" additivity="false"> <level value="debug" /> <appender-ref ref="STDOUT" /> </logger> <logger name="l_find" additivity="false"> <level value="debug" /> <appender-ref ref="STDOUT" /> </logger> <logger name="l_put" additivity="false"> <level value="debug" /> <appender-ref ref="STDOUT" /> </logger> <logger name="l_get" additivity="false"> <level value="debug" /> <appender-ref ref="STDOUT" /> </logger> <logger name="l_structure" additivity="false"> <level value="debug" /> <appender-ref ref="STDOUT" /> </logger>
package test; import static java.lang.System.out; import net.proteanit.demo.util.HashMap; public class MapTest { public static void main(String[] args) { HashMap<String, Integer> dbgMap = new HashMap<String, Integer>(); for (int i = 0; i < 20; i++) { // Generate random two-letter string String s = net.proteanit.util.StringUtils.randomString(2); dbgMap.put(s, i); } dbgMap.put("A", 100); // Dump Map to show entries dbgMap.dumpMap(); // Calculate the degree of linearity in the Map out.printf("Map has a linearity of %.3f\n", dbgMap.getLinearity()); out.println(dbgMap.get("A").toString()); // Various ops to get the loggers working out.println(dbgMap.containsKey("A")); out.println(dbgMap.containsValue(2)); } } As you can see, there are two additional methods: dumpMap and getLinearity. The former shows the buckets of the map, which consist of 0 to n Entry objects. The best case scenario is that there be only one Entry in a bucket, giving a lookup order of O(1). Owing to the structure of the map and the implementation of the hashCode method of its key class however, there could be several Entry instances in the same bucket. A lookup operation might now encounter a degree of linearity, detracting from O(1), as entries (implemented as a linked list) need to be iterated to find the correct value. It's this linearity that getLinearity attempts to measure, by taking into account the number of multiple-entry buckets. The source code is contained in /src in the jar.
Only registered users can write comments!
Powered by !JoomlaComment 3.26
3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved." |
|||||
| Last Updated ( Friday, 09 July 2010 08:47 ) |



