1 19 20 package org.netbeans.modules.javacore.scanning; 21 22 import org.netbeans.modules.javacore.JMManager; 23 24 31 final class IntSet { 32 static class Entry { 33 int value; 34 int hash; 35 Entry next; 36 37 Entry(int v, int h, Entry n) { 38 value = v; 39 hash = h; 40 next = n; 41 } 42 } 43 44 private Entry[] table; 45 private int size; 46 47 private static final int LOAD_FACTOR = 2; 48 private static final int GROWTH_FACTOR = 2; 49 50 public IntSet() { 51 this(2048); 55 } 56 57 public IntSet(int capacity) { 58 table = new Entry[capacity]; 59 } 60 61 public boolean add(int x) { 62 if (contains(x)) 63 return false; 64 65 if (size > table.length / LOAD_FACTOR) 66 resize(); 67 68 int h = hash(x); 69 int idx = indexFor(h, table.length); 70 Entry e = new Entry(x, h, table[idx]); 71 table[idx] = e; 72 size++; 73 return true; 74 } 75 76 public boolean contains(int x) { 77 int h = hash(x); 78 Entry e = table[indexFor(h, table.length)]; 79 while (e != null) { 80 if (e.value == x) 81 return true; 82 e = e.next; 83 } 84 return false; 85 } 86 87 public int[] toArray() { 88 int[] arr = new int[size]; 89 int n = 0; 90 Entry eNext; 91 for (int i = 0; i < table.length; i++) 92 for(Entry e = table[i]; e != null; e = e.next) 93 arr[n++] = e.value; 94 assert n == size; 95 return arr; 96 } 97 98 private void resize() { 99 Entry[] newt = new Entry[table.length * GROWTH_FACTOR]; 100 101 Entry eNext; 102 for(int i = 0; i < table.length; i++) 103 for(Entry e = table[i]; e != null; e = eNext) { 104 int idx = indexFor(e.hash, newt.length); 105 eNext = e.next; 106 e.next = newt[idx]; 107 newt[idx] = e; 108 } 109 table = newt; 110 JMManager.getLog().log("IntSet: table doubled to " + table.length); 111 } 112 113 115 125 private static int hash(int h) { 126 h += ~(h << 9); 127 h ^= (h >>> 14); 128 h += (h << 4); 129 h ^= (h >>> 10); 130 return h; 131 } 132 133 136 private static int indexFor(int h, int length) { 137 return h & (length-1); 138 } 139 } 140 | Popular Tags |