Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void hashMapInsight(HashMap<String, Integer> hashMap) {
- Class clsHashMap = hashMap.getClass();
- try {
- Field table = clsHashMap.getDeclaredField("table");
- table.setAccessible(true);
- Object[] buckets = (Object[]) table.get(hashMap);
- // System.out.println(Arrays.toString(bucket));
- Class Node = Class.forName("java.util.HashMap$Node");
- int maxLength = 0;
- StringBuilder longest = new StringBuilder();
- for (Object bucketNode : buckets) {
- if (bucketNode != null) {
- int i = 1;
- StringBuilder tmp = new StringBuilder();
- Field keyString = Node.getDeclaredField("key");
- keyString.setAccessible(true);
- tmp.append(keyString.get(bucketNode));
- tmp.append(" -> ");
- Field next = Node.getDeclaredField("next");
- next.setAccessible(true);
- while ((bucketNode = next.get(bucketNode)) != null) {
- i++;
- tmp.append(keyString.get(bucketNode));
- tmp.append(" -> ");
- }
- if (i > maxLength) {
- maxLength = i;
- longest = tmp;
- }
- }
- }
- longest.delete(longest.length() - 4, longest.length());
- System.out.println("hashmap table size is: " + buckets.length);
- System.out.println("longest linkedlist is: " + longest.toString());
- System.out.println("Max length of hashmap bucket is: " + maxLength);
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- int m;
- // SeparateChainingHashST<String, Integer> map;
- HashMap<String, Integer> hashMap;
- for (int i = 4; i < 20; i++) {
- m = 1 << i;
- hashMap = new HashMap<>(m);
- // map = new SeparateChainingHashST<>(m);
- for (int j = 0; j < (int) (m * 0.75); j++) {
- String t = Integer.toString((int) (Math.random() * (m * 0.75)));
- // t = Integer.toString(j);
- // map.put(t, 0);
- hashMap.put(t, 0);
- }
- // System.out.println("-------------my hashMap-------------");
- // map.bucketStat();
- System.out.println("------------java hashMap------------");
- hashMapInsight(hashMap);
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement