import java.util.*;   class TestCollection13{       public static void main(String args[]){           HashMap&lt;Integer,String&gt; hm=new HashMap&lt;Integer,String&gt;();            hm.put(100,"Amit");           hm.put(101,"Vijay");           hm.put(102,"Rahul");            for(Map.Entry m:hm.entrySet()){               System.out.println(m.getKey()+" "+m.getValue());           }       }   }     in this above HaspMap program i can not understand the logic behind this for loop . why Map.Entry is needed and what is the function of entrySet() ??  help me regarding this please . thanks in advance
827
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?  Will the ordering of elements depend on the specific map implementation that I have for the interface?
20509
I have a small code example I want to include in the Javadoc comment for a method.    /**  * -- ex: looping through List of Map objects --  * &lt;code&gt;  * for (int i = 0; i &lt; list.size(); i++) {  *      Map map = (Map)list.get(i);  *      System.out.println(map.get("wordID"));  *      System.out.println(map.get("word"));  * }  * &lt;/code&gt;  *   * @param query - select statement  * @return List of Map objects  */   The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.    -- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }  Parameters query - - select statement  Returns: List of Map objects    I guess I am wrong in assuming the code tag would handle line breaks.  What is the best way to format code examples in Javadoc comments ?
37684
I'm trying create a Map using a name field as key.  Sample code:  Set&lt;String&gt; priceBooksNames = new Set&lt;String&gt;(); priceBooksNames.add('LN-200'); priceBooksNames.add('LN-100');  Map&lt;string,PriceBook2&gt; priceBooks = new Map&lt;string,PriceBook2&gt;([SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]); system.debug(priceBooks.get('LN-100')); //this is returning NULL   I can see on console that setId on map is not getting the name field value.  VARIABLE_ASSIGNMENT [5]|priceBooks|{"serId":1,"value":{"01sb0000000hiqQAAQ":{"serId":2,"value":{"Name":"LN-100 ADULTOS","Id":"01sb0000000hiqQAAQ"}},"01sb0000000hiqGAAQ":{"serId":3,"value":{"Name":"LN-200 EMPRESAS","Id":"01sb0000000hiqGAAQ"}}}}   What I'm going wrong?
27628
How would you initialise a static Map in Java?  Method one: static initialiser  Method two: instance initialiser (anonymous subclass) or some other method?  What are the pros and cons of each?  Here is an example illustrating the two methods:  import java.util.HashMap; import java.util.Map;  public class Test {     private static final Map&lt;Integer, String&gt; myMap = new HashMap&lt;&gt;();     static {         myMap.put(1, "one");         myMap.put(2, "two");     }      private static final Map&lt;Integer, String&gt; myMap2 = new HashMap&lt;&gt;(){         {             put(1, "one");             put(2, "two");         }     }; }
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.
102352
I have a HashMap (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected?  If I do map.clear() and those objects that were in the table are not referenced anywhere else, will they get garbage collected?  What is the fastest way, to actually remove all entries from the table, but also destroy those objects.
33779
I came across some very strange behaviour when working with a Map with Decimal keys today. It seems like the Decimal type can't handle Integer assignments properly, but allows them nonetheless. I've written some example code demonstrating the problem:  Map&lt;Decimal, String&gt; m = new Map&lt;Decimal, String&gt;(); m.put(1234, 'Integer key');  m.put(1234.0, 'Decimal key'); m.put(1234.5, 'Decimal Unique key');  System.debug(m.get(1234));      // =&gt; Integer key, why was this not overwritten if 1234 == 1234.0? System.debug(m.get(1234.0));    // =&gt; Decimal key System.debug(m.get(1234.5));    // =&gt; Decimal Unique key  System.debug(m);        //Order of insertion matters, newest value does not override existing one but is not shown on map printout... for(Decimal d : m.keySet()){     System.debug(d);    //...unless you print it out yourself, because this loop shows all the keys }  //Sanity check System.debug(1234 == 1234.0); //True  //Digging deeper Decimal fake_d = 1234; Decimal real_d = 1234.0; Integer real_i = 1234; //Integer fake_i = 1234.0; //Illegal assignment, typechecking only works one way, it seems  //More sanity checks System.debug(fake_d == real_d); //True (Except when used in a Map, apparently) System.debug(fake_d == real_i); //True  System.debug(m.get(real_i)); // =&gt; Integer key System.debug(m.get(fake_d)); // =&gt; Integer key, even with fake_d explicitely declared as a Decimal type, it still pretends to be an Integer. System.debug(m.get(real_d)); // =&gt; Decimal key   I found this behaviour when I tried to fetch a value from a map using a Decimal sObject field, only to find that the keys I used to populate the Map (coming from a different Decimal field) were interpreted as Integers since they had no real decimal digits.  Maybe using Decimals as Map keys is not supported for some reason? Is it expected behaviour for 1234 and 1234.0 being distinct values in this case or is this an oversight in the Map implementation?
34669
I have a Map which is to be modified by several threads concurrently.   There seem to be three different synchronized Map implementations in the Java API:   Hashtable Collections.synchronizedMap(Map) ConcurrentHashMap   From what I understand, Hashtable is an old implementation (extending the obsolete Dictionary class), which has been adapted later to fit the Map interface. While it is synchronized, it seems to have serious  and is discouraged for new projects.  But what about the other two? What are the differences between Maps returned by Collections.synchronizedMap(Map) and ConcurrentHashMaps? Which one fits which situation?
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?
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
56910
The function of this apex code is when Account has no Contacts the first contact created become the primary contact and when there is existing primary contact it cannot assign a other primary contact on account. Please help to optimized my code to easy understand.Thanks for the help.  public class CreatePrimaryContactHandler {     public static void createPrimary(List&lt;Contact&gt; contactList)     {        Set&lt;Id&gt; accountId = new Set&lt;Id&gt;();         for(Contact c : contactList)         {             accountId.add(c.AccountId);         }         List&lt;Contact&gt; allContact = [SELECT Id, Account.Id, Primary_Contact__c FROM Contact WHERE (Account.Id IN : accountId)];         Map&lt;Id, List&lt;Contact&gt;&gt; acctContactMap = new Map&lt;Id, List&lt;Contact&gt;&gt;();             for(Id aId : accountId)             {              List&lt;Contact&gt; conList = new List&lt;Contact&gt;();                 for(Contact allcont : allContact)                 {                     if(allcont.AccountId == aId)                     {                     conList.add(allcont);                     }                 }                 acctContactMap.put(aId, conList);             }             for(Id accId : acctContactMap.keySet())             {                 Integer count = 0;                 for(Contact c : contactList)                 {                     if(c.AccountId == accId &amp;&amp; c.Primary_Contact__c)                     {                         count++;                     }                 }                 if(count &lt;= 1)                 {                     List&lt;Contact&gt; cList = acctContactMap.get(accId);                     Contact primary;                     Boolean isPrimary = false;                     for(Contact cont : cList)                     {                         if(cont.Primary_Contact__c)                         {                             isPrimary = true;                         }                     }                     for(Contact cont : contactList)                     {                         if(cont.AccountId == accId)                         {                             if(cont.Primary_Contact__c)                             {                                 if(primary != null)                                 {                                     primary.Primary_Contact__c = false;                                      isPrimary = false;                                 }                                 else if(isPrimary)                                 {                                 cont.addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                                 }                                     else                                     {                                         cont.Primary_Contact__c = true;                                         isPrimary = true;                                     }                             }                                    else if(!isPrimary)                                 {                                     cont.Primary_Contact__c = true;                                     isPrimary = true;                                     primary = cont;                                 }                         }                     }                 }                 else                 {                     contactList.get(0).addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                 }         }       } }   This is the Trigger  trigger CheckPrimaryContact on Contact (before insert,after update,before update){     if(trigger.IsInsert &amp;&amp; trigger.IsBefore){         CreatePrimaryContactHandler.createPrimary(trigger.new);     }     if(trigger.IsBefore &amp;&amp; trigger.IsUpdate){         CreatePrimaryContactHandler.createPrimary(trigger.new);     } }
115801
I'm a beginner in Java.  Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried Map and Set, but they weren't what I was looking for.
102371
A while ago, I had a discussion with a colleague about how to insert values in STL . I preferred map[key] = value; because it feels natural and is clear to read whereas he preferred map.insert(std::make_pair(key, value)). I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The  simply says: &quot;Strictly speaking, this member function is unnecessary: it exists only for convenience.&quot; Can anybody tell me that reason, or am I just dreaming that there is one?
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?
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
27319
I want to use a collection initializer for the next bit of code:  public Dictionary&lt;int, string&gt; GetNames() {     Dictionary&lt;int, string&gt; names = new Dictionary&lt;int, string&gt;();     names.Add(1, "Adam");     names.Add(2, "Bart");     names.Add(3, "Charlie");     return names; }   So typically it should be something like:  return new Dictionary&lt;int, string&gt; {     1, "Adam",    2, "Bart"    ...   But what is the correct syntax for this?
8608
It's clear that a search performance of the generic HashSet&lt;T&gt; class is higher than of the generic List&lt;T&gt; class. Just compare the hash-based key with the linear approach in the List&lt;T&gt; class.  However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the HashSet&lt;T&gt;.  My question: where is the break-even?  To simplify the scenario (and to be fair) let's assume that the List&lt;T&gt; class uses the element's Equals() method to identify an item.