下面列出了java.util.HashMap#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Object removeAdditionalInstanceField(Object obj, String key) {
if (obj == null)
throw new NullPointerException("object must not be null");
if (key == null)
throw new NullPointerException("key must not be null");
HashMap<String, Object> objectFields;
synchronized (additionalFields) {
objectFields = additionalFields.get(obj);
if (objectFields == null)
return null;
}
synchronized (objectFields) {
return objectFields.remove(key);
}
}
protected void verifyTwoHDFSFiles(VM vm, String uniqueName) throws Exception {
HashMap<String, HashMap<String, String>> filesToEntriesMap = createFilesAndEntriesMap(vm, uniqueName, uniqueName);
assertTrue( "there should be exactly two files, but there are " + filesToEntriesMap.size(), filesToEntriesMap.size() == 2);
long timestamp = Long.MAX_VALUE;
String olderFile = null;
String newFile = null;
for (Map.Entry<String, HashMap<String, String> > e : filesToEntriesMap.entrySet()) {
String fileName = e.getKey().substring(0, e.getKey().length() - AbstractHoplogOrganizer.SEQ_HOPLOG_EXTENSION.length());
long newTimeStamp = Long.parseLong(fileName.substring(fileName.indexOf("-")+1, fileName.lastIndexOf("-")));
if (newTimeStamp < timestamp) {
olderFile = e.getKey();
timestamp = newTimeStamp;
}
}
verifyInEntriesMap(filesToEntriesMap.get(olderFile), 1, 8 , "vm0");
verifyInEntriesMap(filesToEntriesMap.get(olderFile), 4, 10 , "vm1");
filesToEntriesMap.remove(olderFile);
verifyInEntriesMap(filesToEntriesMap.values().iterator().next(), 10, 18, "vm0");
verifyInEntriesMap(filesToEntriesMap.values().iterator().next(), 14, 20, "vm1");
}
@Override
protected void inputsToModel(boolean create) {
if (create) {
e = new Verb();
} else {
HashMap<String, Verb> verbs = parent.getVerbs();
verbs.remove(e.getHashKey());
}
e.setId(id.getText());
e.setState(state.getText());
e.setTarget(target.getText());
e.setIcon(icon.getText());
parent.addVerb(e);
// TODO UNDO OP
// UndoOp undoOp = new UndoAddElement(doc, e);
// Ctx.project.getUndoStack().add(undoOp);
Ctx.project.setModified();
}
/**
* Converts a map into a valid hash table, i.e.
* it removes all the 'null' values from the map.
*/
public static <K, V> Hashtable<K, V> mapToHashtable(Map<K, V> map) {
HashMap<K, V> m = new HashMap<K, V>(map);
if (m.containsKey(null)) m.remove(null);
for (Iterator<?> i = m.values().iterator(); i.hasNext(); )
if (i.next() == null) i.remove();
return new Hashtable<K, V>(m);
}
/**
* If the user has specified a default look and feel, use that.
* Otherwise use the look and feel that's native to this platform.
* If this code is called after the application has explicitly
* set it's look and feel, do nothing.
*
* @see #maybeInitialize
*/
private static void initializeDefaultLAF(Properties swingProps)
{
if (getLAFState().lookAndFeel != null) {
return;
}
// Try to get default LAF from system property, then from AppContext
// (6653395), then use cross-platform one by default.
String lafName = null;
HashMap lafData =
(HashMap) AppContext.getAppContext().remove("swing.lafdata");
if (lafData != null) {
lafName = (String) lafData.remove("defaultlaf");
}
if (lafName == null) {
lafName = getCrossPlatformLookAndFeelClassName();
}
lafName = swingProps.getProperty(defaultLAFKey, lafName);
try {
setLookAndFeel(lafName);
} catch (Exception e) {
throw new Error("Cannot load " + lafName);
}
// Set any properties passed through AppContext (6653395).
if (lafData != null) {
for (Object key: lafData.keySet()) {
UIManager.put(key, lafData.get(key));
}
}
}
public void testRemove() throws Exception {
HashMap<String, Integer> map = new HashMap<String, Integer>();
addItems(map);
map.remove("three");
assertNull(map.get("three"));
}
/**
* searches a list of suitable url normalizer plugins for the given scope.
*
* @param scope
* Scope for which we seek a url normalizer plugin.
* @return List - List of extensions to be used for this scope. If none,
* returns null.
* @throws PluginRuntimeException
*/
private List<Extension> findExtensions(String scope) {
String[] orders = null;
String orderlist = conf.get("urlnormalizer.order." + scope);
if (orderlist == null) orderlist = conf.get("urlnormalizer.order");
if (orderlist != null && !orderlist.trim().equals("")) {
orders = orderlist.trim().split("\\s+");
}
String scopelist = conf.get("urlnormalizer.scope." + scope);
Set<String> impls = null;
if (scopelist != null && !scopelist.trim().equals("")) {
String[] names = scopelist.split("\\s+");
impls = new HashSet<String>(Arrays.asList(names));
}
Extension[] extensions = this.extensionPoint.getExtensions();
HashMap<String, Extension> normalizerExtensions = new HashMap<String, Extension>();
for (int i = 0; i < extensions.length; i++) {
Extension extension = extensions[i];
if (impls != null && !impls.contains(extension.getClazz()))
continue;
normalizerExtensions.put(extension.getClazz(), extension);
}
List<Extension> res = new ArrayList<Extension>();
if (orders == null) {
res.addAll(normalizerExtensions.values());
} else {
// first add those explicitly named in correct order
for (int i = 0; i < orders.length; i++) {
Extension e = normalizerExtensions.get(orders[i]);
if (e != null) {
res.add(e);
normalizerExtensions.remove(orders[i]);
}
}
// then add all others in random order
res.addAll(normalizerExtensions.values());
}
return res;
}
public static void main(String[] args) {
HashMap<Integer, Integer> map = new HashMap<>();
ArrayDeque<Integer> deque = new ArrayDeque<>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int max = 0;
for (int i = 0; i < n; i++) {
/* Remove old value (if necessary) */
if (i >= m) {
int old = deque.removeFirst();
if (map.get(old) == 1) {
map.remove(old);
} else {
map.merge(old, -1, Integer::sum);
}
}
/* Add new value */
int num = scan.nextInt();
deque.addLast(num);
map.merge(num, 1, Integer::sum);
max = Math.max(max, map.size());
/* If all integers are unique, we have found our largest
possible answer, so we can break out of loop */
if (max == m) {
break;
}
}
scan.close();
System.out.println(max);
}
private static void removeMetadataAttribute(CloudBlobWrapper blob,
String key) {
HashMap<String, String> metadata = blob.getMetadata();
if (metadata != null) {
metadata.remove(key);
blob.setMetadata(metadata);
}
}
public void removeParam(String name ){
if(!params.getValue().containsKey(name))
return;
HashMap<String, String> props = new HashMap<String, String>();
if(params.getValue() != null ){ //replace to trigger property change
props.putAll(params.getValue());
}
Element paramElement = findParamElement(name);
if(paramElement != null ){
itemNode.removeChild(paramElement);
}
props.remove(name);
params.setValue(props);
}
public void testCheckboxAttributesEL () throws Exception {
WebResponse resp = wc.getResponse(webedTestLocation
+ "/test/ListTag/testCheckboxAttributesEL.jsp");
WebForm form = resp.getForms()[0];
Node node = getLastElementChild(form.getDOMSubtree());
checkCommonCheckboxAttributes(node);
HashMap knownContents = getKnownContents();
for (int i = 0; i < getElementChildCount(node); i=i+2) {
Node option = getNthElementChild(node, i);
checkType(option, "input");
checkNameAttribute(option, "listTest");
String objectId = option.getAttributes().getNamedItem("value").getNodeValue();
String value = option.getNextSibling().getNodeValue();
if (selectedObjectId().equals(objectId)) checkAttribute(option, "checked", "checked");
String text = (String)knownContents.get(objectId);
assertNotNull("Unexpected option - value: "+ objectId + " with content: " + value, text);
assertEquals("Incorrect option content", text, value);
knownContents.remove(objectId);
}
assertTrue("Items expected but not found: " + knownContents, knownContents.isEmpty());
//Submit the form to check that no problems occur
form.submit();
// Check for the correct forward
assertEquals("Incorrect Result", webedTestApplication
+ "/test/defaultForward.html", wc.getCurrentPage().getURL().getPath());
}
public DummyRevisionHistory build() {
HashMap<String, DummyCommit> index = new HashMap<>(runningIndex);
for (String key : indexedCommitsBuilder().build().keySet()) {
index.remove(key);
}
indexedCommitsBuilder().putAll(index);
return internalBuild();
}
/**
* Removes given CQ from the cqMap..
*/
public void removeCq(String cqName) {
// On server side cqName will be server side cqName.
synchronized (cqQueryMapLock) {
HashMap tmpCqQueryMap = new HashMap(cqQueryMap);
tmpCqQueryMap.remove(cqName);
this.cqNameToUserAttributesMap.remove(cqName);
cqQueryMap = tmpCqQueryMap;
}
}
public V remove(Object key) {
synchronized(this) {
HashMap<K,V> new_map = new HashMap<>(map);
V res = new_map.remove(key);
this.map = new_map;
return res;
}
}
public void unbindStickStyle(WXComponent component) {
WXScroller scroller = component.getParentScroller();
if (scroller == null) {
return;
}
HashMap<String, WXComponent> stickyMap = mStickyMap.get(scroller
.getRef());
if (stickyMap == null) {
return;
}
stickyMap.remove(component.getRef());
}
@Test
public void testAdvanced() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.getConfig().disableObjectReuse();
DataSet<Integer> data = env.fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
DataSet<Integer> data2 = env.fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
DataSet<Tuple2<Integer, Integer>> data3 = data.cross(data2);
// count
long numEntries = data3.count();
assertEquals(100, numEntries);
// collect
ArrayList<Tuple2<Integer, Integer>> list = (ArrayList<Tuple2<Integer, Integer>>) data3.collect();
// set expected entries in a hash map to true
HashMap<Tuple2<Integer, Integer>, Boolean> expected = new HashMap<Tuple2<Integer, Integer>, Boolean>();
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
expected.put(new Tuple2<Integer, Integer>(i, j), true);
}
}
// check if all entries are contained in the hash map
for (int i = 0; i < 100; i++) {
Tuple2<Integer, Integer> element = list.get(i);
assertEquals(expected.get(element), true);
expected.remove(element);
}
}
private ProjectThing makeProjectThing(String type, final HashMap<String,String> ht_attributes) {
try {
type = type.toLowerCase();
// debug:
//Utils.log2("TMLHander.makeProjectThing for type=" + type);
long id = -1;
final String sid = ht_attributes.remove("id");
if (null != sid) {
id = Long.parseLong(sid);
}
long oid = -1;
final String soid = ht_attributes.remove("oid");
if (null != soid) {
oid = Long.parseLong(soid);
}
Boolean expanded = new Boolean(false); // default: collapsed
Object eob = ht_attributes.remove("expanded");
if (null != eob) {
expanded = new Boolean((String)eob);
}
String title = ht_attributes.remove("title");
TemplateThing tt = this.project.getTemplateThing(type);
if (null == tt) {
Utils.log("No template for type " + type);
return null;
}
ProjectThing pt = new ProjectThing(tt, this.project, id, null == title ? type : title, null);
pt.addToDatabase();
ht_pt_expanded.put(pt, expanded);
// store the oid vs. pt relationship to fill in the object later.
if (-1 != oid) {
ht_oid_pt.put(new Long(oid), pt);
}
return pt;
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
private List prepareItemTextAttachment(ItemTextIfc itemText, boolean isEditPendingAssessmentFlow){
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
Set attachmentSet = new HashSet();
if (itemText != null){
attachmentSet = itemText.getItemTextAttachmentSet();
}
HashMap map = getResourceIdHash(attachmentSet);
ArrayList newAttachmentList = new ArrayList();
AssessmentService assessmentService = new AssessmentService();
String protocol = ContextUtil.getProtocol();
List refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if (refs!=null && refs.size() > 0){
Reference ref;
for(int i=0; i<refs.size(); i++) {
ref = (Reference) refs.get(i);
String resourceId = ref.getId();
if (map.get(resourceId) == null){
// new attachment, add
log.debug("**** ref.Id="+ref.getId());
log.debug("**** ref.name="+ref.getProperties().getProperty(
ref.getProperties().getNamePropDisplayName()));
ItemTextAttachmentIfc newAttach = assessmentService.createItemTextAttachment(
itemText,
ref.getId(), ref.getProperties().getProperty(
ref.getProperties().getNamePropDisplayName()),
protocol, isEditPendingAssessmentFlow);
newAttachmentList.add(newAttach);
}
else{
// attachment already exist, let's add it to new list and
// check it off from map
newAttachmentList.add((ItemTextAttachmentIfc)map.get(resourceId));
map.remove(resourceId);
}
}
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
return newAttachmentList;
}
else if (itemText == null) {
return new ArrayList();
}
else {
ArrayList attachmentList = new ArrayList();
Set<ItemTextAttachmentIfc> itemTextAttachmentSet = itemText.getItemTextAttachmentSet();
for (Iterator<ItemTextAttachmentIfc> it = itemTextAttachmentSet.iterator(); it.hasNext();) {
attachmentList.add(it.next());
}
return attachmentList;
}
}
/**
* @see org.quartz.spi.JobStore#replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger)
*/
public boolean replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger) throws JobPersistenceException {
boolean found;
synchronized (lock) {
// remove from triggers by FQN map
TriggerWrapper tw = triggersByKey.remove(triggerKey);
found = (tw != null);
if (found) {
if (!tw.getTrigger().getJobKey().equals(newTrigger.getJobKey())) {
throw new JobPersistenceException("New trigger is not related to the same job as the old trigger.");
}
tw = null;
// remove from triggers by group
HashMap<TriggerKey, TriggerWrapper> grpMap = triggersByGroup.get(triggerKey.getGroup());
if (grpMap != null) {
grpMap.remove(triggerKey);
if (grpMap.size() == 0) {
triggersByGroup.remove(triggerKey.getGroup());
}
}
// remove from triggers array
Iterator<TriggerWrapper> tgs = triggers.iterator();
while (tgs.hasNext()) {
tw = tgs.next();
if (triggerKey.equals(tw.key)) {
tgs.remove();
break;
}
}
timeTriggers.remove(tw);
try {
storeTrigger(newTrigger, false);
} catch(JobPersistenceException jpe) {
storeTrigger(tw.getTrigger(), false); // put previous trigger back...
throw jpe;
}
}
}
return found;
}
/**
* Remove a specific pointer in the given hashmap
*
* @param hm hashmap of size, pointers
* @param size size in bytes
* @param ptr pointer to be removed
*/
private static void remove(HashMap<Long, Set<Pointer>> hm, long size, Pointer ptr) {
hm.get(size).remove(ptr);
if (hm.get(size).isEmpty())
hm.remove(size);
}