I am starting to learn java and going through the following issue While trying to update values(Hashset) of ConcurrentHashMap when iterating over it - ConcurrentModificationError is shown while debugging - although the code didn't crash This is the scenario: concurrentMap = Key -&gt; A Value -&gt; [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;] Key -&gt; B value -&gt; [&quot;a&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;]  when i try to remove &quot;a&quot; while iterating over A it fails to update the hashset properly and fails to loop I saw the hashset update as follows [a, b, c, d] [b,c]  How can I remove 'a' from key A while i am iterating over A and update the hashSet properly ? private ConcurrentMap&lt;String, HashSet&lt;String&gt;&gt; concurrentMap = new ConcurrentHashMap&lt;&gt;();  private void parseItems(Item testItem) throws Exception {          Map&lt;String, HashSet&lt;String&gt;&gt; itemMap = ConcurrentHashMap &lt;&gt;(Myclass.getIdMap(testItem));         concurrentMap = new ConcurrentHashMap&lt;&gt;(itemMap);         for (String type : concurrentMap.keySet()) {             for (String id : concurrentMap.get(type)) {                 if (type.equals(&quot;MyType&quot;)) {                     myList = function1(MyType, id);                 } else {                     myList = function2(defaultType, id, &quot;ID&quot;);                 }                 removeParsedIdFromCurrentMap(type, id);                  for (Item item : myList) {                     ConcurrentMap&lt;String, HashSet&lt;String&gt;&gt; newItemConcurrentMap = new ConcurrentHashMap&lt;&gt;(Myclass.getIdMap(item));                     addToConcurentMap(newItemConcurrentMap);                 }             }         }     }  private void removeParsedIdFromCurrentMap(String type, String id) {         HashSet&lt;String&gt; currentIdSet = concurrentMap.get(type);         //This removes the value 'a'         if (currentIdSet != null) {             Iterator&lt;String&gt; iter = currentIdSet.iterator();             while (iter.hasNext()) {                 String toRemoveId = iter.next();                 if (toRemoveId.contains(id)) {                     iter.remove();                 }             }             //How can I update the values of key A while iterating A?              updateConcurrentMap();         }      }  private void addToConcurentMap(ConcurrentMap&lt;IOMType, HashSet&lt;String&gt;&gt; newItemConcurrentMap ) {         for (String type : newItemConcurrentMap .keySet()) {             for (String id : newItemConcurrentMap .get(type)) {                 if (!checkIdParsed(type, id)) {                     concurrentMap.putIfAbsent(type, new HashSet&lt;&gt;());                     concurrentMap.get(type).add(id);                 }             }         }     }
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.
90963
Did you know that :  Map&lt;Object,Object&gt; m1 = new HashMap&lt;Object, Object&gt;(); Map&lt;Object,Object&gt; m2 = new HashMap&lt;Object, Object&gt;(); System.out.println("m1.equals(m2) = "+m1.equals(m2)); System.out.println("m1.keySet().equals(m2.keySet()) = "             +m1.keySet().equals(m2.keySet())); System.out.println("m1.entrySet().equals(m2.entrySet()) = "             +m1.entrySet().equals(m2.entrySet())); System.out.println("m1.values().equals(m2.values()) = "             +m1.values().equals(m2.values()));   would output :  m1.equals(m2) = true m1.keySet().equals(m2.keySet()) = true m1.entrySet().equals(m2.entrySet()) = true m1.values().equals(m2.values()) = false   This is caused by the fact that AbstractCollection (which HashMap$Values inherits from) does not overrides #equals().  Do you have an idea why this is so ?
3385
In the two following snippets, is the first one safe or must you do the second one?  By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created?  Or must you copy the reference to a new variable "local" to each iteration of the loop?  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Thread thread = new Thread(() =&gt; f.DoSomething());     threads.Add(thread);     thread.Start(); }   -  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Foo f2 = f;     Thread thread = new Thread(() =&gt; f2.DoSomething());     threads.Add(thread);     thread.Start(); }   Update: As pointed out in Jon Skeet's answer, this doesn't have anything specifically to do with threading.
7577
What issues / pitfalls must be considered when overriding equals and hashCode?
112547
I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :  public interface Translator {     public void loadTranslations();     public String getTranslation(String key); }   loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.  My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.  A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.  Thanks for your help !
14775
There is a case where a map will be constructed, and once it is initialized, it will never be modified again.  It will however, be accessed (via get(key) only) from multiple threads.  Is it safe to use a java.util.HashMap in this way?  (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice.  Hence, this question is not "Which one should I use?" nor is it a performance question.  Rather, the question is "Would it be safe?")
77839
when I try to run the code below I am getting this error: 'Too many DML rows: 10001'. The object that I am trying to update is one of the main object in the org. so it has multiples triggers, workflows, etc. and one API that runs all day long. I am trying to update 29000 records. can anybody please tell me why i am getting this error or if something is wrong with the code. I will appreciate any help!  Class code:     public class updateNRProdObject{    public Decimal Debug{ get; set; }         public void updateObject(){     List&lt;NRProducts__c&gt; products = [SELECT id  FROM NRProducts__c WHERE  Active__c = true];   Debug = products.size();    for(NRProducts__c p : products){       p.Active__c=false;    }    update products ;   } }
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
31501
Are sObjects supported as the keys for ?  I thought they were, but it appears that any subsequent changes to the key sObject break the mapping to the value.  This might be better shown with an anonymous apex example (API v27.0).  Map&lt;OpportunityLineItem, string&gt; testMap = new Map&lt;OpportunityLineItem, string&gt;(); OpportunityLineItem testOli = new OpportunityLineItem(); testOli.Description = 'foo'; testMap.put(testOli, 'bar'); System.assert(testMap.containsKey(testOli)); string mapValue = testMap.get(testOli); System.assertEquals('bar', mapValue);  // After this the OLI will no longer be a key in the map. testOli.OpportunityId = '0064000000RB2eJ';  System.assert(testMap.containsKey(testOli), 'Expected to still contain OLI'); string mapValue2 = testMap.get(testOli); System.assertEquals('bar', mapValue2, 'OLI instance still expected to map to string bar');   This fails for me with:     System.AssertException: Assertion Failed: Expected to still contain OLI   Is this the expected behaviour?
101111
We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?     Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:   execution of AfterInsert caused by: System.StringException: Invalid   id: () : [] () : []: ()   What I am trying to accomplish is:   When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set&lt;ID> Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE      Trigger:   trigger MSI_UserTrigger on User (after insert) {       if(Trigger.isAfter){          if(Trigger.isInsert){              MSIUserTriggerHandler.executeAfterInsert(Trigger.new);          }      } }      Class:   public with sharing class MSIUserTriggerHandler {     private static final String COMMUNITY_PROFILE = 'Community Knowledge User';     private MSIUserTriggerHandler() {}      public static void executeAfterInsert(List&lt;User&gt; newList){         setCreatedCommunityUsers(newList);     }      private static void setCreatedCommunityUsers(List&lt;User&gt; newList){         List&lt;User&gt; usersWithContacts = new List&lt;User&gt;();         List&lt;Contact&gt; contactsToUpdate = new List&lt;Contact&gt;();         Set&lt;ID&gt; contactIds = new Set&lt;ID&gt;();          for(User u: newList){             if(u.ContactId == null &amp;&amp; u.ContactId == ''){                 continue;             }             if((u.ContactId != null &amp;&amp; u.ContactId != '') &amp;&amp; u.Profile.Name == COMMUNITY_PROFILE &amp;&amp; u.isActive == true){                 contactIds.add(u.ContactId);             }         }          for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){             if(!c.Community_User_Created__c){                 c.Community_User_Created__c = true;                 contactsToUpdate.add(c);             }         }         update contactsToUpdate;     } }   Am I not adding the ID correctly to the Set&lt;ID>, or am I querying wrong in my for(Contacts) loop?
16676
Eclipse is giving me a warning of the following form:     Type safety: Unchecked cast from Object to HashMap   This is from a call to an API that I have no control over which returns Object:  HashMap&lt;String, String&gt; getItems(javax.servlet.http.HttpSession session) {   HashMap&lt;String, String&gt; theHash = (HashMap&lt;String, String&gt;)session.getAttribute("attributeKey");   return theHash; }   I'd like to avoid Eclipse warnings, if possible, since theoretically they indicate at least a potential code problem.  I haven't found a good way to eliminate this one yet, though.  I can extract the single line involved out to a method by itself and add @SuppressWarnings("unchecked") to that method, thus limiting the impact of having a block of code where I ignore warnings.  Any better options?  I don't want to turn these warnings off in Eclipse.  Before I came to the code, it was simpler, but still provoked warnings:  HashMap getItems(javax.servlet.http.HttpSession session) {   HashMap theHash = (HashMap)session.getAttribute("attributeKey");   return theHash; }   Problem was elsewhere when you tried to use the hash you'd get warnings:  HashMap items = getItems(session); items.put("this", "that");  Type safety: The method put(Object, Object) belongs to the raw type HashMap.  References to generic type HashMap&lt;K,V&gt; should be parameterized.
45361
What is the right way of initializing a static map? Do we need a static function that will initialize it?
80355
I have this struct:  struct Map {     public int Size;      public Map ( int size )     {         this.Size = size;     }      public override string ToString ( )     {         return String.Format ( "Size: {0}", this.Size );     } }   When using array, it works:  Map [ ] arr = new Map [ 4 ] {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  arr [ 2 ].Size = 0;   But when using List, it doesn't compile:  List&lt;Map&gt; list = new List&lt;Map&gt; ( ) {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  list [ 2 ].Size = 0;   Why?
11908
I'm trying to map the maximal amount of days without rain using the TRMM dataset in Google Earth Engine. I'm doing this by iterating over the collection and if no rain has fallen, one gets added to the cell (code below). When rain has fallen the value gets multiplied by 0 so the "counter" is reset. Then I would like to store each result of each iteration in a Image collection and then select the maximum value to get the longest consecutive dry period.  But that is the theory. When I put this in a script I get an error while adding the image of one iteration to a list.   Does anyone know why this is and how this can be solved?  Code:  var list = []; function drylength(current, previous){   var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');   var sum = mask.add(previous).multiply(mask);    list.push(sum);   return sum; }  var dataset = TRMM .filterDate("2015-01-01","2015-02-01") .sort('system:time_start:');  var totalPrecipitation = dataset.iterate(drylength, dataset.max() .remap([0], [0], 0, "precipitation") .rename('precipitation'));  print(list); print(totalPrecipitation); Map.addLayer(ee.Image(totalPrecipitation), imageVisParam);   Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one?   Here is an image of the error:    Errors written if image is not visible or for search engines:  Failed to decode JSON. Error: Field 'value' of object '{"type":"ArgumentRef","value":null}' is missing or null. Object: {"type":"ArgumentRef","value":null}.   and:  Unknown variable references: [_MAPPING_VAR_0_0, _MAPPING_VAR_0_1].
17471
I'm getting the error below when trying to loop through a listbox and then remove the item.     List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.   foreach (string s in listBox1.Items) {     MessageBox.Show(s);     //do stuff with (s);     listBox1.Items.Remove(s); }   How can I remove the item and still loop through the contents?
124250
I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...  I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the composites hash map. I was able to get around this by calling to_owned on the vector. Is this the right way to handle this?  I also see that when I build the code, I get warnings about unused code for warning: struct is never constructed: 'Sieve' and warning: method is never used: 'new', am I constructing them incorrectly?  use std::collections::HashMap;  struct Sieve {     composites: HashMap&lt;u64, Vec&lt;u64&gt;&gt;,     x: u64, }  impl Sieve {     fn new() -&gt; Sieve {         Sieve {             composites: HashMap::new(),             x: 2,         }     } }  impl Iterator for Sieve {     type Item = u64;      fn next(&amp;mut self) -&gt; Option&lt;u64&gt; {         let x = self.x;         self.x = self.x + 1;         match self.composites.get(&amp;x) {             Some(numbers) =&gt; {                 for _num in numbers.to_owned() {                     self.composites                         .entry(x + _num)                         .and_modify(|v| v.push(_num))                         .or_insert(vec![_num]);                 }                 self.composites.remove(&amp;x);                 self.next()             }             None =&gt; {                 self.composites.insert(x * x, vec![x]);                 Some(x)             }         }     } }  fn main() {     let mut sieve = Sieve::new();      println!("{:?}", sieve.next()); // 2     println!("{:?}", sieve.next()); // 3     println!("{:?}", sieve.next()); // 5     println!("{:?}", sieve.next()); // 7 }   .  I , this made it difficult to get feedback on. I have refactored the code to use iterators
3732
For example:  javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.