下面列出了java.util.Hashtable#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void whenRemovePair_thenCheckKeyAndValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
// old way
/* if (table.get(new Word("cat")).equals("an animal")) {
table.remove(new Word("cat"));
}*/
// new way
boolean result = table.remove(new Word("cat"), "an animal");
assertThat(result, is(false));
}
private DirContext doGetContext(String principal, String credentials, boolean explicitlyDisablePooling) {
Hashtable<String, Object> env = getAuthenticatedEnv(principal, credentials);
if(explicitlyDisablePooling) {
env.remove(SUN_LDAP_POOLING_FLAG);
}
DirContext ctx = createContext(env);
try {
DirContext processedDirContext = authenticationStrategy.processContextAfterCreation(ctx, principal, credentials);
return processedDirContext;
}
catch (NamingException e) {
closeContext(ctx);
throw LdapUtils.convertLdapException(e);
}
}
/**
* Write #includes for boxed IDLEntity references.
* @param refHash Hashtable loaded with referenced types
* @param p The output stream.
*/
protected void writeIDLEntityIncludes(
Hashtable refHash,
IndentingWriter p )
throws IOException {
Enumeration refEnum = refHash.elements();
while ( refEnum.hasMoreElements() ) {
Type t = (Type)refEnum.nextElement();
if ( t.isCompound() ) {
CompoundType ct = (CompoundType)t;
if ( ct.isIDLEntity() ) { //select IDLEntities
writeInclude( ct,0,!isThrown,p );
refHash.remove( ct.getQualifiedName() ); //avoid another #include
}
}
}
}
/**
* Write #includes for boxed IDLEntity references.
* @param refHash Hashtable loaded with referenced types
* @param p The output stream.
*/
protected void writeIDLEntityIncludes(
Hashtable refHash,
IndentingWriter p )
throws IOException {
Enumeration refEnum = refHash.elements();
while ( refEnum.hasMoreElements() ) {
Type t = (Type)refEnum.nextElement();
if ( t.isCompound() ) {
CompoundType ct = (CompoundType)t;
if ( ct.isIDLEntity() ) { //select IDLEntities
writeInclude( ct,0,!isThrown,p );
refHash.remove( ct.getQualifiedName() ); //avoid another #include
}
}
}
}
/**
* Write #includes for boxed IDLEntity references.
* @param refHash Hashtable loaded with referenced types
* @param p The output stream.
*/
protected void writeIDLEntityIncludes(
Hashtable refHash,
IndentingWriter p )
throws IOException {
Enumeration refEnum = refHash.elements();
while ( refEnum.hasMoreElements() ) {
Type t = (Type)refEnum.nextElement();
if ( t.isCompound() ) {
CompoundType ct = (CompoundType)t;
if ( ct.isIDLEntity() ) { //select IDLEntities
writeInclude( ct,0,!isThrown,p );
refHash.remove( ct.getQualifiedName() ); //avoid another #include
}
}
}
}
private void preprocess(String _property, Hashtable<String, String> _propertyTable) {
String value = _propertyTable.get(_property);
if(value!=null) {
setProperty(_property, value);
_propertyTable.remove(_property);
}
}
/** Frees all listeners etc from given workspace. */
void detachWorkspace(
Workspace workspace, Hashtable workspace2Menu, Hashtable menu2Workspace, Hashtable workspace2Listener,
JMenu menu
) {
JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) workspace2Menu.get(workspace);
workspace2Menu.remove(workspace);
menu2Workspace.remove(workspace2Listener.get(workspace));
workspace2Listener.remove(workspace);
menu.remove(menuItem);
}
@Override
protected void parentDeleteRow(int row)
{
String key = (String) parentValueAt(row, 0);
Hashtable<String, Vector<String>> arrays = AndroidEditor.instance()
.getArrays();
arrays.remove(key);
}
@SuppressWarnings("unchecked")
private static Hashtable<String, Object> convertNativeConfig(
Hashtable<String, Object> stanzaTable) {
// convert SCDynamicStore realm structure to Java realm structure
Hashtable<String, ?> realms =
(Hashtable<String, ?>) stanzaTable.get("realms");
if (realms != null) {
stanzaTable.remove("realms");
Hashtable<String, Object> realmsTable = convertRealmConfigs(realms);
stanzaTable.put("realms", realmsTable);
}
WrapAllStringInVector(stanzaTable);
if (DEBUG) System.out.println("stanzaTable : " + stanzaTable);
return stanzaTable;
}
@SuppressWarnings("unchecked")
private static Hashtable<String, Object> convertNativeConfig(
Hashtable<String, Object> stanzaTable) {
// convert SCDynamicStore realm structure to Java realm structure
Hashtable<String, ?> realms =
(Hashtable<String, ?>) stanzaTable.get("realms");
if (realms != null) {
stanzaTable.remove("realms");
Hashtable<String, Object> realmsTable = convertRealmConfigs(realms);
stanzaTable.put("realms", realmsTable);
}
WrapAllStringInVector(stanzaTable);
if (DEBUG) System.out.println("stanzaTable : " + stanzaTable);
return stanzaTable;
}
public ReachableObjects(JavaHeapObject root,
final ReachableExcludes excludes) {
this.root = root;
final Hashtable<JavaHeapObject, JavaHeapObject> bag = new Hashtable<JavaHeapObject, JavaHeapObject>();
final Hashtable<String, String> fieldsExcluded = new Hashtable<String, String>(); //Bag<String>
final Hashtable<String, String> fieldsUsed = new Hashtable<String, String>(); // Bag<String>
JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() {
public void visit(JavaHeapObject t) {
// Size is zero for things like integer fields
if (t != null && t.getSize() > 0 && bag.get(t) == null) {
bag.put(t, t);
t.visitReferencedObjects(this);
}
}
public boolean mightExclude() {
return excludes != null;
}
public boolean exclude(JavaClass clazz, JavaField f) {
if (excludes == null) {
return false;
}
String nm = clazz.getName() + "." + f.getName();
if (excludes.isExcluded(nm)) {
fieldsExcluded.put(nm, nm);
return true;
} else {
fieldsUsed.put(nm, nm);
return false;
}
}
};
// Put the closure of root and all objects reachable from root into
// bag (depth first), but don't include root:
visitor.visit(root);
bag.remove(root);
// Now grab the elements into a vector, and sort it in decreasing size
JavaThing[] things = new JavaThing[bag.size()];
int i = 0;
for (Enumeration e = bag.elements(); e.hasMoreElements(); ) {
things[i++] = (JavaThing) e.nextElement();
}
ArraySorter.sort(things, new Comparer() {
public int compare(Object lhs, Object rhs) {
JavaThing left = (JavaThing) lhs;
JavaThing right = (JavaThing) rhs;
int diff = right.getSize() - left.getSize();
if (diff != 0) {
return diff;
}
return left.compareTo(right);
}
});
this.reachables = things;
this.totalSize = root.getSize();
for (i = 0; i < things.length; i++) {
this.totalSize += things[i].getSize();
}
excludedFields = getElements(fieldsExcluded);
usedFields = getElements(fieldsUsed);
}
public ReachableObjects(JavaHeapObject root,
final ReachableExcludes excludes) {
this.root = root;
final Hashtable<JavaHeapObject, JavaHeapObject> bag = new Hashtable<JavaHeapObject, JavaHeapObject>();
final Hashtable<String, String> fieldsExcluded = new Hashtable<String, String>(); //Bag<String>
final Hashtable<String, String> fieldsUsed = new Hashtable<String, String>(); // Bag<String>
JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() {
public void visit(JavaHeapObject t) {
// Size is zero for things like integer fields
if (t != null && t.getSize() > 0 && bag.get(t) == null) {
bag.put(t, t);
t.visitReferencedObjects(this);
}
}
public boolean mightExclude() {
return excludes != null;
}
public boolean exclude(JavaClass clazz, JavaField f) {
if (excludes == null) {
return false;
}
String nm = clazz.getName() + "." + f.getName();
if (excludes.isExcluded(nm)) {
fieldsExcluded.put(nm, nm);
return true;
} else {
fieldsUsed.put(nm, nm);
return false;
}
}
};
// Put the closure of root and all objects reachable from root into
// bag (depth first), but don't include root:
visitor.visit(root);
bag.remove(root);
// Now grab the elements into a vector, and sort it in decreasing size
JavaThing[] things = new JavaThing[bag.size()];
int i = 0;
for (Enumeration e = bag.elements(); e.hasMoreElements(); ) {
things[i++] = (JavaThing) e.nextElement();
}
ArraySorter.sort(things, new Comparer() {
public int compare(Object lhs, Object rhs) {
JavaThing left = (JavaThing) lhs;
JavaThing right = (JavaThing) rhs;
int diff = right.getSize() - left.getSize();
if (diff != 0) {
return diff;
}
return left.compareTo(right);
}
});
this.reachables = things;
this.totalSize = root.getSize();
for (i = 0; i < things.length; i++) {
this.totalSize += things[i].getSize();
}
excludedFields = getElements(fieldsExcluded);
usedFields = getElements(fieldsUsed);
}
@Override
public void removeAttribute(String name) {
Hashtable<String,Object> atts = cfSCRIPTJava.javaClassFactory.getAttributes();
atts.remove(name);
}
public ReachableObjects(JavaHeapObject root,
final ReachableExcludes excludes) {
this.root = root;
final Hashtable<JavaHeapObject, JavaHeapObject> bag = new Hashtable<JavaHeapObject, JavaHeapObject>();
final Hashtable<String, String> fieldsExcluded = new Hashtable<String, String>(); //Bag<String>
final Hashtable<String, String> fieldsUsed = new Hashtable<String, String>(); // Bag<String>
JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() {
public void visit(JavaHeapObject t) {
// Size is zero for things like integer fields
if (t != null && t.getSize() > 0 && bag.get(t) == null) {
bag.put(t, t);
t.visitReferencedObjects(this);
}
}
public boolean mightExclude() {
return excludes != null;
}
public boolean exclude(JavaClass clazz, JavaField f) {
if (excludes == null) {
return false;
}
String nm = clazz.getName() + "." + f.getName();
if (excludes.isExcluded(nm)) {
fieldsExcluded.put(nm, nm);
return true;
} else {
fieldsUsed.put(nm, nm);
return false;
}
}
};
// Put the closure of root and all objects reachable from root into
// bag (depth first), but don't include root:
visitor.visit(root);
bag.remove(root);
// Now grab the elements into a vector, and sort it in decreasing size
JavaThing[] things = new JavaThing[bag.size()];
int i = 0;
for (Enumeration e = bag.elements(); e.hasMoreElements(); ) {
things[i++] = (JavaThing) e.nextElement();
}
ArraySorter.sort(things, new Comparer() {
public int compare(Object lhs, Object rhs) {
JavaThing left = (JavaThing) lhs;
JavaThing right = (JavaThing) rhs;
int diff = right.getSize() - left.getSize();
if (diff != 0) {
return diff;
}
return left.compareTo(right);
}
});
this.reachables = things;
this.totalSize = root.getSize();
for (i = 0; i < things.length; i++) {
this.totalSize += things[i].getSize();
}
excludedFields = getElements(fieldsExcluded);
usedFields = getElements(fieldsUsed);
}
public void installIfNeeded()
throws BundleException
{
final ConfigurationAdmin ca = DirDeployerImpl.caTracker.getService();
if (pids == null && ca != null) {
try {
fileLastModified = file.lastModified();
// List with all PIDs that is created from the current file.
final List<String> pidList = new ArrayList<String>();
// List with all PIDs for factory configurations that are defined in the
// current file, used for duplicate detection.
final List<String> pidListFactory = new ArrayList<String>();
final Hashtable<String, Object>[] configs = loadCMDataFile(file);
for (final Hashtable<String, Object> config : configs) {
final String pid = (String) config.get(CMDataReader.SERVICE_PID);
config.remove("service.bundleLocation");
final String fpid = (String) config.get(CMDataReader.FACTORY_PID);
Configuration cfg;
if (fpid == null) {
// Non-factory Configuration
if (pidList.contains(pid)) {
DirDeployerImpl.logErr("Skipping dupplicated configuration "
+ "with pid='" + pid + "' found in "
+ file, null);
continue;
}
final File otherFile = installedCfgs.get(pid);
if (!file.equals(otherFile)) {
DirDeployerImpl.log("Overwriting configuration with pid='" + pid
+ "' defined in '" + otherFile + "'.");
}
cfg = ca.getConfiguration(pid, null);
// Make sure that an existing configuration is unbound from
// location.
if (cfg.getBundleLocation() != null) {
cfg.setBundleLocation(null);
}
} else {
// Factory configuration
if (pidListFactory.contains(pid)) {
DirDeployerImpl.logErr("Skipping non-unique factory "
+ "configuration with service.pid='" + pid
+ "' found in " + file, null);
continue;
}
pidListFactory.add(pid);
cfg = ca.createFactoryConfiguration(fpid, null);
DirDeployerImpl.log("Created factory config with pid '"
+ cfg.getPid()
+ "' for file configuration with service.pid '"
+ pid + "'.");
filePidToCmPid.put(getFilePidForPid(pid), cfg.getPid());
}
cfg.update(config);
pidList.add(cfg.getPid());
installedCfgs.put(cfg.getPid(), file);
}
pids = pidList.toArray(new String[pidList.size()]);
DirDeployerImpl.log("installed " + this);
} catch (final Exception e) {
DirDeployerImpl.log("Failed to install " + this + "; " + e, e);
}
} else {
DirDeployerImpl.log("already installed " + this);
}
if (pids != null) {
saveState();
}
}
public void test (TestHarness harness)
{
// The toString tests have been commented out as they currently
// print in reverse order from the std JDK. Uncomment these if
// we change our implementation to output in the same order.
Hashtable hash = new Hashtable(13);
harness.check (hash.toString(), "{}");
harness.check (hash.isEmpty());
hash.put(new Integer(1), "one");
hash.put(new Integer(2), "two");
hash.put(new Integer(3), "three");
hash.put(new Integer(4), "four");
hash.put(new Integer(5), "five");
// Rehash should have just happened.
hash.put(new Integer(6), "six");
hash.put(new Integer(7), "seven");
// Rehash should have just happened.
hash.put(new Integer(8), "eight");
hash.put(new Integer(9), "nine");
hash.put(new Integer(10), "ten");
hash.put(new Integer(11), "eleven");
hash.put(new Integer(12), "twelve");
hash.put(new Integer(13), "thirteen");
hash.put(new Integer(14), "fourteen");
// Rehash should have just happened.
hash.put(new Integer(15), "fifteen");
// harness.check (hash.toString());
harness.check (! hash.isEmpty());
harness.check (hash.size(), 15);
Integer key = new Integer(13);
String val = (String) hash.get(key);
hash.put(key, val.toUpperCase());
// harness.check (hash.toString());
harness.check (hash.size(), 15);
harness.check (hash.containsKey(key));
harness.check (! hash.contains("thirteen"));
harness.check (hash.contains("THIRTEEN"));
hash.remove(key);
// harness.check (hash.toString());
harness.check (hash.size(), 14);
hash.clear();
harness.check (hash.toString(), "{}");
harness.check (hash.size(), 0);
}
/**
* Parses stanza names and values from configuration file to
* stanzaTable (Hashtable). Hashtable key would be stanza names,
* (libdefaults, realms, domain_realms, etc), and the hashtable value
* would be another hashtable which contains the key-value pairs under
* a stanza name. The value of this sub-hashtable can be another hashtable
* containing another sub-sub-section or a vector of strings for
* final values (even if there is only one value defined).
* <p>
* For duplicates section names, the latter overwrites the former. For
* duplicate value names, the values are in a vector in its appearing order.
* </ol>
* Please note that this behavior is Java traditional. and it is
* not the same as the MIT krb5 behavior, where:<ol>
* <li>Duplicated root sections will be merged
* <li>For duplicated sub-sections, the former overwrites the latter
* <li>Duplicate keys for values are always saved in a vector
* </ol>
* @param v the strings in the file, never null, might be empty
* @throws KrbException if there is a file format error
*/
@SuppressWarnings("unchecked")
private Hashtable<String,Object> parseStanzaTable(List<String> v)
throws KrbException {
Hashtable<String,Object> current = stanzaTable;
for (String line: v) {
// There are 3 kinds of lines
// 1. a = b
// 2. a = {
// 3. }
if (line.equals("}")) {
// Go back to parent, see below
current = (Hashtable<String,Object>)current.remove(" PARENT ");
if (current == null) {
throw new KrbException("Unmatched close brace");
}
} else {
int pos = line.indexOf('=');
if (pos < 0) {
throw new KrbException("Illegal config content:" + line);
}
String key = line.substring(0, pos).trim();
String value = trimmed(line.substring(pos+1));
if (value.equals("{")) {
Hashtable<String,Object> subTable;
if (current == stanzaTable) {
key = key.toLowerCase(Locale.US);
}
subTable = new Hashtable<>();
current.put(key, subTable);
// A special entry for its parent. Put whitespaces around,
// so will never be confused with a normal key
subTable.put(" PARENT ", current);
current = subTable;
} else {
Vector<String> values;
if (current.containsKey(key)) {
Object obj = current.get(key);
// If a key first shows as a section and then a value,
// this is illegal. However, we haven't really forbid
// first value then section, which the final result
// is a section.
if (!(obj instanceof Vector)) {
throw new KrbException("Key " + key
+ "used for both value and section");
}
values = (Vector<String>)current.get(key);
} else {
values = new Vector<String>();
current.put(key, values);
}
values.add(value);
}
}
}
if (current != stanzaTable) {
throw new KrbException("Not closed");
}
return current;
}
/**
* Parses stanza names and values from configuration file to
* stanzaTable (Hashtable). Hashtable key would be stanza names,
* (libdefaults, realms, domain_realms, etc), and the hashtable value
* would be another hashtable which contains the key-value pairs under
* a stanza name. The value of this sub-hashtable can be another hashtable
* containing another sub-sub-section or a vector of strings for
* final values (even if there is only one value defined).
* <p>
* For duplicates section names, the latter overwrites the former. For
* duplicate value names, the values are in a vector in its appearing order.
* </ol>
* Please note that this behavior is Java traditional. and it is
* not the same as the MIT krb5 behavior, where:<ol>
* <li>Duplicated root sections will be merged
* <li>For duplicated sub-sections, the former overwrites the latter
* <li>Duplicate keys for values are always saved in a vector
* </ol>
* @param v the strings in the file, never null, might be empty
* @throws KrbException if there is a file format error
*/
@SuppressWarnings("unchecked")
private Hashtable<String,Object> parseStanzaTable(List<String> v)
throws KrbException {
Hashtable<String,Object> current = stanzaTable;
for (String line: v) {
// There are 3 kinds of lines
// 1. a = b
// 2. a = {
// 3. }
if (line.equals("}")) {
// Go back to parent, see below
current = (Hashtable<String,Object>)current.remove(" PARENT ");
if (current == null) {
throw new KrbException("Unmatched close brace");
}
} else {
int pos = line.indexOf('=');
if (pos < 0) {
throw new KrbException("Illegal config content:" + line);
}
String key = line.substring(0, pos).trim();
String value = trimmed(line.substring(pos+1));
if (value.equals("{")) {
Hashtable<String,Object> subTable;
if (current == stanzaTable) {
key = key.toLowerCase(Locale.US);
}
subTable = new Hashtable<>();
current.put(key, subTable);
// A special entry for its parent. Put whitespaces around,
// so will never be confused with a normal key
subTable.put(" PARENT ", current);
current = subTable;
} else {
Vector<String> values;
if (current.containsKey(key)) {
Object obj = current.get(key);
// If a key first shows as a section and then a value,
// this is illegal. However, we haven't really forbid
// first value then section, which the final result
// is a section.
if (!(obj instanceof Vector)) {
throw new KrbException("Key " + key
+ "used for both value and section");
}
values = (Vector<String>)current.get(key);
} else {
values = new Vector<String>();
current.put(key, values);
}
values.add(value);
}
}
}
if (current != stanzaTable) {
throw new KrbException("Not closed");
}
return current;
}
public void Compare(String p_CFHT_strFilename, Hashtable<Object, Integer> p_CFHT_htHashTable) {
try {
int nRecordNumber = 0;
int nCount = 1;
int nBufferLength = 12;
int nKey;
long lGetValue;
long lCount;
boolean blnKeyIsThere;
Object objGetValue;
Hashtable<Object, Integer> htHashTable = p_CFHT_htHashTable;
System.out.println("I am comparing the file with the hashtable");
// Get a channel for the file and provide a place
// in memory to put the bytes with a buffer
File f = new File(p_CFHT_strFilename);
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
ByteBuffer bb = java.nio.ByteBuffer.allocate(nBufferLength);
// while we are not at the end of the file
while (nCount != 0 && nCount != -1) {
// Starting at byte number (nRecordNumber*nBufferLength)
// read the next nBufferLength bytes from the file into
// buffer bb and rewind to the beginning of the buffer
nCount = fc.read(bb, nRecordNumber * nBufferLength);
bb.rewind();
// If we are not at the end of the file
if (nCount != -1 && nCount != 0) {
// Read the first 4 bytes and then the next 8 bytes and
// print the results to the screen.
nKey = bb.getInt();
lCount = bb.getLong();
// Checking the Hashtable to see if the random number is there
blnKeyIsThere = htHashTable.containsKey(" " + nKey);
// If the random number is there then get the value
// associated with this
// key. Compare this value with the occurences value in the
// file. If they are
// the same then increase the nMatches count, if they are
// different print their
// values to the screen and increase the differences count.
// In each case
// remove the key from the hashtable. If the random number
// is not there
// then print this to the screen also.
if (blnKeyIsThere) {
objGetValue = htHashTable.get(" " + nKey);
lGetValue = Long.parseLong(objGetValue.toString());
if (lCount == lGetValue) {
nMatches++;
htHashTable.remove(" " + nKey);
} else {
nOccurenceDiffs++;
htHashTable.remove(" " + nKey);
}
} else {
nNotInHashTable++;
}
}
// clear the buffer and increment the nRecordNumber (this will
// ensure the next 12 bytes are read into the buffer.
bb.clear();
nRecordNumber++;
}
// close the FileInputStream (this consequently closes the
// FileChannel
fis.close();
// Check to see if there are any keys left in the hashtable. If
// there aren't
// then print all the results to the screen, if there are then
// calculate how
// many keys are left in the hashtable and print all the results to
// the screen.
if (htHashTable.isEmpty()) {
nTotalDiffs = nOccurenceDiffs + nNotInHashTable;
} else {
nNotInFile = htHashTable.size();
nTotalDiffs = nOccurenceDiffs + nNotInHashTable + nNotInFile;
}
} catch (IOException e) {
System.out.println("Error occured in ComparingFileHashTable class: " + e);
}
}
@Test
public void whenPutAndGet_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String definition = table.get(word);
assertEquals("an animal", definition);
definition = table.remove(word);
assertEquals("an animal", definition);
}