I have a multimap called clientPrinterConnections that maps printer names to SocketConnections in a many to many manner. When I close a SocketConnection, I want to remove every entry that uses it. I thought Multimap implements ConcurrentMap (it seems like it did in 8.0.0 but not 9.0.0) so I did it the easy way.      for (Map.Entry&lt;String, List&lt;SocketConnection&gt;&gt; e: clientPrinterConnections.entrySet()) {         if (e.getValue().contains(connection)) {             clientPrinterConnections.removeValue(e.getKey(),connection);         }     }   It ends up that doesn't work, and it throws a ConcurrentModificationException. I can't really use an iterator though due to needing a removeValue call.      Iterator iter = clientPrinterConnections.entrySet().iterator();     while(iter.hasNext()) {         Map.Entry&lt;String, List&lt;SocketConnection&gt;&gt; pair = (Map.Entry)iter.next();         if (pair.getValue().contains(connection)) {             //this deletes all connections to the specific printer             iter.remove();             //this throws the same exception as before             clientPrinterConnections.removeValue(pair.getKey(),connection);         }     }   I can just compile a list of things to delete like this,      ArrayList&lt;String&gt; itemsToDelete = new ArrayList();     for (Map.Entry&lt;String, List&lt;SocketConnection&gt;&gt; e: clientPrinterConnections.entrySet()) {         if (e.getValue().contains(connection)) {             itemsToDelete.add(e.getKey());         }     }     for (String s: itemsToDelete){         clientPrinterConnections.removeValue(s,connection);     }   but that seems messy. Is there a more elegant way to do this? I can imagine some situations where just compiling a list wouldn't be an adequate fix.
78
We all know you can't do the following because of ConcurrentModificationException:  for (Object i : l) {     if (condition(i)) {         l.remove(i);     } }   But this apparently works sometimes, but not always. Here's some specific code:  public static void main(String[] args) {     Collection&lt;Integer&gt; l = new ArrayList&lt;&gt;();      for (int i = 0; i &lt; 10; ++i) {         l.add(4);         l.add(5);         l.add(6);     }      for (int i : l) {         if (i == 5) {             l.remove(i);         }     }      System.out.println(l); }   This, of course, results in:  Exception in thread "main" java.util.ConcurrentModificationException   Even though multiple threads aren't doing it. Anyway.  What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?  I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.
26298
std::map&lt;std::string, std::string&gt; myMap;  std::map&lt;std::string, std::string&gt;::iterator i = m_myMap.find(some_key_string); if(i == m_imagesMap.end())     return NULL;  string *p = &amp;i-&gt;first;   Is the last line valid?  I want to store this pointer p somewhere else, will it be valid for the whole program life?  But what will happen if I add some more elements to this map (with other unique keys) or remove some other keys, won’t it reallocate this string (key-value pair), so the p will become invalid?
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
73495
With a TreeMap it's trivial to provide a custom Comparator, thus overriding the semantics provided by Comparable objects added to the map. HashMaps however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'.  I suspect it would be both easy and useful to design an interface and to retrofit this into HashMap (or a new class)? Something like this, except with better names:    interface Hasharator&lt;T&gt; {     int alternativeHashCode(T t);     boolean alternativeEquals(T t1, T t2);   }    class HasharatorMap&lt;K, V&gt; {     HasharatorMap(Hasharator&lt;? super K&gt; hasharator) { ... }   }    class HasharatorSet&lt;T&gt; {     HasharatorSet(Hasharator&lt;? super T&gt; hasharator) { ... }   }   The  problem gets a trivial solution:   new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY);   Would this be doable, or can you see any fundamental problems with this approach?  Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.)  EDIT: Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;)  EDIT: Changed title to no longer mention "Comparator"; I suspect this was a bit confusing.    EDIT: Accepted answer with relation to performance; would love a more specific answer!  EDIT: There is an implementation; see the accepted answer below.  EDIT: Rephrased the first sentence to indicate more clearly that it's the side-loading I'm after (and not ordering; ordering does not belong in HashMap).
17653
Some of code I read in trigger is like this    for(account a: [select id  from account where id in: mapAccount.keySet()]) {     //code      }    some are like   List&lt;Account&gt; listAccount = [select id  from account where id in: mapAccount.keySet()];   for(Account a: listAccount ){   //coode   }   Are those same from performance view?which one is better?
3248
I have an ArrayList&lt;String&gt;, and I want to remove repeated strings from it. How can I do this?
48735
I recently implemented a class like:  class TestClass : IDisposable {     RegistryKey m_key;     public TestClass()     {         m_key = Registry.CurrentUser.OpenSubKey("Software", false);     }      public void Dispose()     {         // m_key.Dispose();         IDisposable disp = m_key;         disp.Dispose();     } }   If I uncomment the direct call to Dispose, I get error CS0117 ("'Microsoft.Win32.RegistryKey' does not contain a definition for 'Dispose'").  Some Googling led me to , where I learned what was going on, so I now understand the mechanics of it.  The  documentation suggests that the author would prefer that I call Close() instead of Dispose(), but doesn't explain why.  What is the purpose of this pattern (which I think I've seen it in the IO classes as well)?  In light of the fact that this was an intentional decision by the class author, how bad is the code above (the call to Dispose through the IDisposable interface)?  It can't be too bad - after all, it's what would happen in a using statement, right?  [edits: 1) changed title from "non-public" to "explicit" 2) removed the explicit implementation from my code, accidentally left in from experimentation]
41570
I am trying to play a map on LAN. But every time I try to log on, I get:     java.net.ConnectException: Connection refused: no further information:   This used to work, but for some reason has stopped all of a sudden. I looked it up online, and everything I found said the firewall just wasn't allowing Java through. I followed tutorials to allow Java through the firewall, but even then it won't work. I know for a fact that I'm putting the IP in correctly, and everything seems to be correct, but yet I still get the same error message.  If it helps any, I'm using MC version 1.8.9 (the map requires it), and I don't have any mods.
110259
Ierator and for-each loop both we use for traverse no of items, I have used for-each many times but I am not clear about iterator, means when we should use ierator. I am studying salesforce workbook example..  global class CustomIterable implements iterator&lt;Account&gt;{    public List&lt;Account&gt; accs {get; set;}   public Integer i {get; set;}    public CustomIterable(){      accs =[SELECT Name fROM Account limit 5];      i = 0;              }   global boolean hasNext(){          if(i &gt;= accs.size()) {          return false;         } else {          return true;         }    }    global Account next(){          if(i == 8){return null;}          i++;          return accs[i-1];     } }   //------------  @isTest(seealldata=true) global class IteratorClass{     public static testmethod void main(){          IteratorClass obj = new IteratorClass();         Iterator&lt;Account&gt; acs =  obj.Iterator();         system.debug(acs);      }     global Iterator&lt;Account&gt; Iterator(){             return new CustomIterable();          }  }
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
70164
Lets say I have this array,  int[] numbers = {1, 3, 4, 9, 2};   How can I delete an element by "name"? , lets say number 4?  Even ArrayList didn't help to delete?  string strNumbers = " 1, 3, 4, 9, 2"; ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' })); numbers.RemoveAt(numbers.IndexOf(4)); foreach (var n in numbers) {     Response.Write(n); }
25533
The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a WeakHashMap or WeakReference and how was it used?
80489
There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.  First type:  List&lt;string&gt; someList = &lt;some way to init&gt; foreach(string s in someList) {    &lt;process the string&gt; }   Other Way:  List&lt;string&gt; someList = &lt;some way to init&gt; someList.ForEach(delegate(string s) {     &lt;process the string&gt; });   I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...
52986
I am trying to add map of map values, I have to intialize the map key first and then try to add value later. Below is the exact logic i am trying to achieve.  Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt; finalMap = new Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt;();  Map&lt;string,List&lt;string&gt;&gt; subMap = new Map&lt;string,List&lt;string&gt;&gt;(); submap.put('One',new list&lt;string&gt;{'One','TWO'});  finalMap.put('SUB1',new Map&lt;string,List&lt;string&gt;&gt;());  //Do some logics and finally try to add the values with the key  finalmap.get('SUB1').put(subMap); //Error as stated below  System.debug(finalmap);      ERROR :Method does not exist or incorrect signature:   [Map&lt;String,List&lt;String&gt;&gt;].put(Map&lt;String,List&lt;String&gt;&gt;)
52257
I'm searching for a possibility to get a list of installed printers. I'm using JDK 1.6 with a Windows operating system. Does anyone know a solution?   Thank you in advance.
53255
In my spring application context file, I have something like:  &lt;util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String"&gt;     &lt;entry key="some_key" value="some value" /&gt;     &lt;entry key="some_key_2" value="some value" /&gt;    &lt;/util:map&gt;   In java class, the implementation looks like:  private Map&lt;String, String&gt; someMap = new HashMap&lt;String, String&gt;(); someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean("someMap");   In Eclipse, I see a warning that says:  Type safety: Unchecked cast from Object to HashMap  What did I do wrong? How do I resolve the issue?