下面列出了java.util.HashMap#clear ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws Exception {
HashMap<Integer, Object> hm = makeMap();
hm = (HashMap<Integer, Object>)hm.clone();
hm.clear();
// There should no longer be a strong reference to testObject
// the WeakReference should be nulled out by GC. If not,
// we will hang here until timed out by the test harness.
Object[] chain = null;
while (wr.get() != null) {
try {
Object[] allocate = new Object[1000000];
allocate[0] = chain;
chain = allocate;
} catch (OutOfMemoryError oome) {
chain = null;
}
System.gc();
Thread.sleep(100);
}
}
@Override
protected Void doInBackground(Void... params) {
HashMap<String, EpisodeCounter> seasons = MizuuApplication.getTvEpisodeDbAdapter().getSeasons(mShowId);
File temp;
for (String key : seasons.keySet()) {
temp = FileUtils.getTvShowSeason(mContext, mShowId, key);
mItems.add(new GridSeason(mContext, mShowId, Integer.valueOf(key), seasons.get(key).getEpisodeCount(), seasons.get(key).getWatchedCount(),
temp.exists() ? temp :
FileUtils.getTvShowThumb(mContext, mShowId)));
}
seasons.clear();
Collections.sort(mItems);
return null;
}
@Override
protected Void doInBackground() throws Exception {
statusBar.updateStatus("删除公会数据");
statusBar.progressBarAnimationStart();
HashMap<String, DBObjectTreeTableNode> map = model.getChangedMap();
Set<String> set = map.keySet();
for ( String userId : set ) {
int option = JOptionPane.showConfirmDialog(null, "您是否要删除公会"+userId+"?", "删除公会成员",
JOptionPane.YES_NO_OPTION);
if ( option == JOptionPane.YES_OPTION ) {
DBObject query = MongoUtil.createDBObject("userId", userId);
//DBObject objectToSave = (DBObject)map.get(userId).getUserObject();
//MongoUtil.saveToMongo(query, objectToSave, databaseName, namespace, collection, true);
MongoUtil.deleteFromMongo(query, databaseName, namespace, collection, true);
JOptionPane.showMessageDialog(null, "账号"+userId+"已经删除");
}
}
map.clear();
statusBar.progressBarAnimationStop();
statusBar.updateStatus("删除公会成员数据");
return null;
}
/**
* 更新该线程下载的完成度
*/
public void updateInfos(String url, ArrayList<FileDownloadManager.DownloadInfo> infos){
ArrayList<String> columns = DownloadDB.TABLES.DOWNLOAD.getTableColumns();
HashMap<String, String> maps = new HashMap<>();
initUpdateDB();
if (mDb == null)
return;
try {
mDb.beginTransaction();
for (FileDownloadManager.DownloadInfo info : infos){
maps.clear();
maps.put(columns.get(4), info.completeSize+"");
String whereClause = columns.get(0)+"=? and "+columns.get(1)+"=?";
String[] whereArgs = new String[]{info.id+"", url};
mDb.update(maps, whereClause, whereArgs);
}
mDb.setTransactionSuccessful();
}catch (Exception e){
e.printStackTrace();
}finally {
mDb.endTransaction();
mDb.close();
}
}
@Override
public void endWindow()
{
if (readingsList.size() == 0) {
return;
}
LOG.info("Input data size: readingsList - " + readingsList.size());
double[] eruptionDuration = new double[readingsList.size()];
int[] waitingTime = new int[readingsList.size()];
for (int i = 0; i < readingsList.size(); i++) {
eruptionDuration[i] = readingsList.get(i).getEruptionDuration();
waitingTime[i] = readingsList.get(i).getWaitingTime();
}
LOG.info("Input data size: eruptionDuration - " + eruptionDuration.length);
LOG.info("Input data size: waitingTime - " + waitingTime.length);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ELAPSEDTIME", elapsedTime);
map.put("ERUPTIONS", eruptionDuration);
map.put("WAITING", waitingTime);
super.process(map);
readingsList.clear();
map.clear();
}
private boolean parseVillageRenamerData(String pData) {
HashMap<String, List<Village>> mappings = new HashMap<>();
try {
JSONObject sectorObject = new JSONObject(pData);
JSONObject data = (JSONObject) sectorObject.get("id");
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String villageId = keys.next();
String groupName = (String) data.get(villageId);
List<Village> groups = mappings.get(groupName);
if (groups == null) {
groups = new LinkedList<>();
mappings.put(groupName, groups);
}
Village v = DataHolder.getSingleton().getVillagesById().get(Integer.parseInt(villageId));
groups.add(v);
}
} catch (JSONException | NumberFormatException e) {
logger.warn("Failed to parse group info from village renamer data");
mappings.clear();
}
if (!mappings.isEmpty()) {
DSWorkbenchMainFrame.getSingleton().fireGroupParserEvent(mappings);
return true;
}
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNodeProcessingSchema(CompareMap oper)
{
CountAndLastTupleTestSink matchSink = new CountAndLastTupleTestSink();
oper.compare.setSink(matchSink);
oper.setKey("a");
oper.setValue(3.0);
oper.setTypeNEQ();
oper.beginWindow(0);
HashMap<String, Number> input = new HashMap<String, Number>();
input.put("a", 2);
input.put("b", 20);
input.put("c", 1000);
oper.data.process(input);
input.clear();
input.put("a", 3);
oper.data.process(input);
oper.endWindow();
// One for each key
Assert.assertEquals("number emitted tuples", 1, matchSink.count);
for (Map.Entry<String, Number> e : ((HashMap<String, Number>)matchSink.tuple).entrySet()) {
if (e.getKey().equals("a")) {
Assert.assertEquals("emitted value for 'a' was ", new Double(2), e.getValue().doubleValue(), 0);
} else if (e.getKey().equals("b")) {
Assert.assertEquals("emitted tuple for 'b' was ", new Double(20), e.getValue().doubleValue(), 0);
} else if (e.getKey().equals("c")) {
Assert.assertEquals("emitted tuple for 'c' was ", new Double(1000), e.getValue().doubleValue(), 0);
}
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public void testNodeProcessingSchema(ExceptMap oper)
{
CountAndLastTupleTestSink exceptSink = new CountAndLastTupleTestSink();
oper.except.setSink(exceptSink);
oper.setKey("a");
oper.setValue(3.0);
oper.setTypeEQ();
oper.beginWindow(0);
HashMap<String, Number> input = new HashMap<String, Number>();
input.put("a", 2);
input.put("b", 20);
input.put("c", 1000);
oper.data.process(input);
input.clear();
input.put("a", 3);
oper.data.process(input);
oper.endWindow();
// One for each key
Assert.assertEquals("number emitted tuples", 1, exceptSink.count);
for (Map.Entry<String, Number> e : ((HashMap<String, Number>)exceptSink.tuple)
.entrySet()) {
if (e.getKey().equals("a")) {
Assert.assertEquals("emitted value for 'a' was ", new Double(2), e
.getValue().doubleValue(), 0);
} else if (e.getKey().equals("b")) {
Assert.assertEquals("emitted tuple for 'b' was ", new Double(20), e
.getValue().doubleValue(), 0);
} else if (e.getKey().equals("c")) {
Assert.assertEquals("emitted tuple for 'c' was ", new Double(1000), e
.getValue().doubleValue(), 0);
}
}
}
public void startScan(int i)
{
Debug.TRACE();
HashMap hashmap = new HashMap();
if (m_LeScanCallback == null)
{
m_LeScanCallback = new f(this, hashmap);
}
hashmap.clear();
Iterator iterator = getConnectedDevices().iterator();
do
{
if (!iterator.hasNext())
{
break;
}
BluetoothDevice bluetoothdevice = (BluetoothDevice)iterator.next();
if (bluetoothdevice.getAddress().startsWith("88:0F:10"))
{
hashmap.put(bluetoothdevice.getAddress(), bluetoothdevice);
Intent intent = new Intent(INTENT_ACTION_DEVICE_FOUND);
intent.putExtra(INTENT_EXTRA_DEVICE, bluetoothdevice);
intent.putExtra(INTENT_EXTRA_PARAM, 0);
c_BroadcastManager.sendBroadcast(intent);
}
} while (true);
m_BluetoothAdapter.startLeScan(m_LeScanCallback);
boolean flag;
if (i > 0)
{
flag = true;
} else
{
flag = false;
}
Debug.ASSERT_TRUE(flag);
m_StopScanRunnable = new g(this);
m_Handler.postDelayed(m_StopScanRunnable, i);
}
@Override
public void clear() {
super.clear();
for (HashMap<?, ?> elementHashMap : deduplicationMapsByKeyGroup) {
elementHashMap.clear();
}
}
private Map<String, String[]> parseMapping(String mappings)
throws PrincipalMappingException {
if (mappings == null) {
return null;
}
HashMap<String, String[]> table = new HashMap<>();
try {
StringTokenizer t = new StringTokenizer(mappings, ";");
if (t.hasMoreTokens()) {
do {
String mapping = t.nextToken();
String principals = mapping.substring(0, mapping.indexOf('='));
String value = mapping.substring(mapping.indexOf('=')+1);
String[] v = value.split(",");
String[] p = principals.split(",");
for (String s : p) {
table.put(s, v);
}
} while(t.hasMoreTokens());
}
return table;
}
catch (Exception e) {
// do not leave table in an unknown state - clear it instead
// no principal mapping will occur
table.clear();
throw new PrincipalMappingException("Unable to load mappings from provided string: " + mappings + " - no principal mapping will be provided.", e);
}
}
private HashMap<String, List<String>> resolveUpAndDownLinks(HashMap<String, List<String>> drilldownListMap,
List<String> baseTool) throws GraphDBException {
HashMap<String, List<String>> mainToolList = new HashMap<>();
List<String> excludeLabels = new ArrayList<>();
excludeLabels.addAll(baseTool);
while (drilldownListMap.size() > 0) {
List<String> labelsTemp = new ArrayList<>();
HashMap<String, List<String>> tempMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : drilldownListMap.entrySet()) {
String tool = entry.getKey();
List<String> uuids = entry.getValue();
mainToolList.put(tool, uuids);
String cypher = buildCypherQuery(tool, "uuid", uuids, excludeLabels, 2);
/* collect all parent or child uuids for current basenode. */
tempMap.putAll(format(executeCypherQuery(cypher), Arrays.asList(tool)));
/* collect the tools as basetool for the next hop in drilldown */
labelsTemp.addAll(Arrays.asList(tool));
}
excludeLabels = (labelsTemp.stream().distinct().collect(Collectors.toList()));
drilldownListMap.clear();
drilldownListMap.putAll(tempMap);
}
return mainToolList;
}
private static void collectMacros(StringBuffer textbuffer, boolean del, HashMap<String, String> ret) throws PreprocessingException {
MacroExtractor me = new MacroExtractor(textbuffer);
me.parse();
if(del)
me.deleteScripts();
ret.clear();
ret.putAll(me.scripts);
}
/**
* @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#validateSearchParameters(java.util.Map)
*/
@Override
public void validateSearchParameters(Map fieldValues) {
super.validateSearchParameters(fieldValues);
HashMap<String, String> fieldsMap = new HashMap<String, String>();
String accountNumber = (String) fieldValues.get("accountCodeOffset");
String objectCode = (String) fieldValues.get("objectCodeOffset");
// Validate the Account Number field is a valid Account Number in the DB
if (StringUtils.isNotEmpty(accountNumber)) {
fieldsMap.clear();
fieldsMap.put(GeneralLedgerConstants.ColumnNames.ACCOUNT_NUMBER, accountNumber);
List<Account> accountNums = (List<Account>) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, fieldsMap);
if (accountNums == null || accountNums.size() <= 0) {
GlobalVariables.getMessageMap().putError("accountNumber", KFSKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Account Number: " + accountNumber });
throw new ValidationException("errors in search criteria");
}
}
// Validate the Object Code field is a valid Object Code in the DB
if (StringUtils.isNotEmpty(objectCode)) {
fieldsMap.clear();
fieldsMap.put(GeneralLedgerConstants.ColumnNames.OBJECT_CODE, objectCode);
List<ObjectCode> objCodes = (List<ObjectCode>) SpringContext.getBean(BusinessObjectService.class).findMatching(ObjectCode.class, fieldsMap);
if (objCodes == null || objCodes.size() <= 0) {
GlobalVariables.getMessageMap().putError(KFSPropertyConstants.OBJECT_CODE, KFSKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Object Code: " + objectCode });
throw new ValidationException("errors in search criteria");
}
}
}
@Override
public void run() {
HashMap<Queue, LinkedList<MessageReference>> refs = new HashMap<>();
runnables.remove(deliveryTime);
final long now = System.currentTimeMillis();
if (now < deliveryTime) {
// Ohhhh... blame it on the OS
// on some OSes (so far Windows only) the precision of the scheduled executor could eventually give
// an executor call earlier than it was supposed...
// for that reason we will schedule it again so no messages are lost!
// we can't just assume deliveryTime here as we could deliver earlier than what we are supposed to
// this is basically a hack to work around an OS or JDK bug!
if (logger.isTraceEnabled()) {
logger.trace("Scheduler is working around OS imprecisions on " +
"timing and re-scheduling an executor. now=" + now +
" and deliveryTime=" + deliveryTime);
}
ScheduledDeliveryHandlerImpl.this.scheduleDelivery(deliveryTime);
}
if (logger.isTraceEnabled()) {
logger.trace("Is it " + System.currentTimeMillis() + " now and we are running deliveryTime = " + deliveryTime);
}
synchronized (scheduledReferences) {
Iterator<RefScheduled> iter = scheduledReferences.iterator();
while (iter.hasNext()) {
MessageReference reference = iter.next().getRef();
if (reference.getScheduledDeliveryTime() > now) {
// We will delivery as long as there are messages to be delivered
break;
}
iter.remove();
metrics.decrementMetrics(reference);
reference.setScheduledDeliveryTime(0);
LinkedList<MessageReference> references = refs.get(reference.getQueue());
if (references == null) {
references = new LinkedList<>();
refs.put(reference.getQueue(), references);
}
if (logger.isTraceEnabled()) {
logger.trace("sending message " + reference + " to delivery, deliveryTime = " + deliveryTime);
}
references.addFirst(reference);
}
if (logger.isTraceEnabled()) {
logger.trace("Finished loop on deliveryTime = " + deliveryTime);
}
}
for (Map.Entry<Queue, LinkedList<MessageReference>> entry : refs.entrySet()) {
Queue queue = entry.getKey();
LinkedList<MessageReference> list = entry.getValue();
if (logger.isTraceEnabled()) {
logger.trace("Delivering " + list.size() + " elements on list to queue " + queue);
}
queue.addHead(list, true);
}
// Just to speed up GC
refs.clear();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNodeProcessingSchema(TopNUnique oper)
{
CollectorTestSink sortSink = new CollectorTestSink();
oper.top.setSink(sortSink);
oper.setN(3);
oper.beginWindow(0);
HashMap<String, Number> input = new HashMap<String, Number>();
input.put("a", 2);
oper.data.process(input);
input.clear();
input.put("a", 20);
oper.data.process(input);
input.clear();
input.put("a", 1000);
oper.data.process(input);
input.clear();
input.put("a", 5);
oper.data.process(input);
input.clear();
input.put("a", 20);
input.put("b", 33);
oper.data.process(input);
input.clear();
input.put("a", 33);
input.put("b", 34);
oper.data.process(input);
input.clear();
input.put("b", 34);
input.put("a", 1);
oper.data.process(input);
input.clear();
input.put("b", 6);
input.put("a", 1001);
oper.data.process(input);
input.clear();
input.put("c", 9);
input.put("a", 5);
oper.data.process(input);
oper.endWindow();
Assert.assertEquals("number emitted tuples", 3, sortSink.collectedTuples.size());
for (Object o: sortSink.collectedTuples) {
log.debug(o.toString());
for (Map.Entry<String, ArrayList<HashMap<Number, Integer>>> e: ((HashMap<String, ArrayList<HashMap<Number, Integer>>>)o).entrySet()) {
if (e.getKey().equals("a")) {
Assert.assertEquals("emitted value for 'a' was ", 3, e.getValue().size());
} else if (e.getKey().equals("b")) {
Assert.assertEquals("emitted tuple for 'b' was ", 3, e.getValue().size());
} else if (e.getKey().equals("c")) {
Assert.assertEquals("emitted tuple for 'c' was ", 1, e.getValue().size());
}
}
}
log.debug("Done testing round\n");
}
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MonthView v;
HashMap<String, Integer> drawingParams = null;
if (convertView != null) {
v = (MonthView) convertView;
// We store the drawing parameters in the view so it can be recycled
drawingParams = (HashMap<String, Integer>) v.getTag();
} else {
v = createMonthView(mContext);
// Set up the new view
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
v.setLayoutParams(params);
v.setClickable(true);
v.setOnDayClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<>();
}
drawingParams.clear();
final int month = (position + mController.getStartDate().get(Calendar.MONTH)) % MONTHS_IN_YEAR;
final int year = (position + mController.getStartDate().get(Calendar.MONTH)) / MONTHS_IN_YEAR + mController.getMinYear();
int selectedDay = -1;
if (isSelectedDayInMonth(year, month)) {
selectedDay = mSelectedDay.day;
}
// Invokes requestLayout() to ensure that the recycled view is set with the appropriate
// height/number of weeks before being displayed.
v.reuse();
drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
v.setMonthParams(drawingParams);
v.invalidate();
return v;
}
public void testFindConstantForKeyValuePairsCombined() {
final String HARDWARE_KEY = "HARDWARE";
final String MODEL_KEY = "MODEL";
final String MANUFACTURER_KEY = "MANUFACTURER";
final String[] array = {
",defaultValue",
"no_comma",
"error_pattern,0.1",
"HARDWARE=grouper:MANUFACTURER=asus,0.3",
"HARDWARE=mako:MODEL=Nexus 4,0.4",
"HARDWARE=manta:MODEL=Nexus 10:MANUFACTURER=samsung,0.2"
};
final String[] failArray = {
",defaultValue",
"HARDWARE=grouper:MANUFACTURER=ASUS,0.3",
"HARDWARE=mako:MODEL=Nexus_4,0.4",
"HARDWARE=mantaray:MODEL=Nexus 10:MANUFACTURER=samsung,0.2"
};
final HashMap<String,String> keyValues = new HashMap<>();
keyValues.put(HARDWARE_KEY, "grouper");
keyValues.put(MODEL_KEY, "Nexus 7");
keyValues.put(MANUFACTURER_KEY, "asus");
assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
keyValues.clear();
keyValues.put(HARDWARE_KEY, "mako");
keyValues.put(MODEL_KEY, "Nexus 4");
keyValues.put(MANUFACTURER_KEY, "LGE");
assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
keyValues.clear();
keyValues.put(HARDWARE_KEY, "manta");
keyValues.put(MODEL_KEY, "Nexus 10");
keyValues.put(MANUFACTURER_KEY, "samsung");
assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
keyValues.put(HARDWARE_KEY, "mantaray");
assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
}
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MonthView v;
HashMap<String, Integer> drawingParams = null;
if (convertView != null) {
v = (MonthView) convertView;
// We store the drawing parameters in the view so it can be recycled
drawingParams = (HashMap<String, Integer>) v.getTag();
} else {
v = createMonthView(mContext);
// Set up the new view
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
v.setLayoutParams(params);
v.setClickable(true);
v.setOnDayClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<String, Integer>();
}
drawingParams.clear();
final int month = position % MONTHS_IN_YEAR;
final int year = position / MONTHS_IN_YEAR + mController.getMinYear();
int selectedDay = -1;
if (isSelectedDayInMonth(year, month)) {
selectedDay = mSelectedDay.day;
}
// Invokes requestLayout() to ensure that the recycled view is set with the appropriate
// height/number of weeks before being displayed.
v.reuse();
drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
v.setMonthParams(drawingParams);
v.invalidate();
return v;
}
/**
* Test node logic emits correct results
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testNodeProcessing() throws Exception
{
DistinctMap<String, Number> oper = new DistinctMap<String, Number>();
CollectorTestSink sortSink = new CollectorTestSink();
oper.distinct.setSink(sortSink);
oper.beginWindow(0);
HashMap<String, Number> input = new HashMap<String, Number>();
input.put("a", 2);
oper.data.process(input);
input.clear();
input.put("a", 2);
oper.data.process(input);
input.clear();
input.put("a", 1000);
oper.data.process(input);
input.clear();
input.put("a", 5);
oper.data.process(input);
input.clear();
input.put("a", 2);
input.put("b", 33);
oper.data.process(input);
input.clear();
input.put("a", 33);
input.put("b", 34);
oper.data.process(input);
input.clear();
input.put("b", 34);
oper.data.process(input);
input.clear();
input.put("b", 6);
input.put("a", 2);
oper.data.process(input);
input.clear();
input.put("c", 9);
oper.data.process(input);
oper.endWindow();
Assert.assertEquals("number emitted tuples", 8, sortSink.collectedTuples.size());
int aval = 0;
int bval = 0;
int cval = 0;
for (Object o: sortSink.collectedTuples) {
for (Map.Entry<String, Integer> e: ((HashMap<String, Integer>)o).entrySet()) {
String key = e.getKey();
if (key.equals("a")) {
aval += e.getValue();
} else if (key.equals("b")) {
bval += e.getValue();
} else if (key.equals("c")) {
cval += e.getValue();
}
}
}
Assert.assertEquals("Total for key \"a\" ", 1040, aval);
Assert.assertEquals("Total for key \"a\" ", 73, bval);
Assert.assertEquals("Total for key \"a\" ", 9, cval);
}