given two strings s and t, I am trying to find the minimum number of steps to make s an anagram of t. For some reason, I get a null pointer exception when trying to get a key from a map, even after I have verified in the if statement that the map does indeed contain the key. Why is this happening? class Solution {     public int minSteps(String s, String t) {         HashMap&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();         for (int i = 0; i &lt; t.length(); i++) {             if (map.containsKey(t.charAt(i))) {                 map.put(t.charAt(i), map.get(t.charAt(i) + 1));             } else {                 map.put(t.charAt(i), 1);             }         }         int steps = 0;         for (int i = 0; i &lt; s.length(); i++) {             if (map.containsKey(s.charAt(i))) {                 int q = map.get(s.charAt(i)); //results in null pointer exception                 if (q &lt; 1) {                     steps++;                 } else {                     map.put(s.charAt(i), q-1);                 }             } else {                 steps++;             }         }         return steps;     } }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
18175
Say I am iterating over a Map in Java... I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in the Javadoc for the Iterator interface remove method:     [...] The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.   I know for sure that I can invoke the remove method without any issues. But while iterating over the Map collection, can I:   Change the value associated with a key with the Map class put method (put with an existing key)? Add a new entry with the Map class put method (put with a new key)? Remove an entry with the Map class remove method?   My guess is that I can probably safely do #1 (put to an existing key) but not safely do #2 or #3.  Thanks in advance for any clarification on this.
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
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?
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
23917
Which is the right thing to do?  if (myObj['key'] == undefined)   or  if (myObj['key'] == null)   or  if (myObj['key'])
116230
We have a user provided string that may contain unicode characters, and we want the robot to type that string.  How do you convert a string into keyCodes that the robot will use? How do you do it so it is also java version independant (1.3 -> 1.6)?  What we have working for "ascii" chars is  //char c = nextChar(); //char c = 'a'; // this works, and so does 'A' char c = 'á'; // this doesn't, and neither does 'Ă' Robot robot = new Robot(); KeyStroke key = KeyStroke.getKeyStroke("pressed " + Character.toUpperCase(c) ); if( null != key ) {   // should only have to worry about case with standard characters   if (Character.isUpperCase(c))   {     robot.keyPress(KeyEvent.VK_SHIFT);   }    robot.keyPress(key.getKeyCode());   robot.keyRelease(key.getKeyCode());    if (Character.isUpperCase(c))   {     robot.keyRelease(KeyEvent.VK_SHIFT);   } }
59373
is it possible to check for a specific key in a map i.e., whether it exists or not in VISUALFORCE page?  Based on this i need to render a pageblocktable.
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");         }     }; }
57540
I'm trying to update an account list and I need to get the Ids when the update fails.  I use the getId() method but for accounts which fail I get null.  It's an update so my account already has an Id.  Is it normal ? If it is, how can I get the Ids list of non-updated accounts ?  Here is my code :  List&lt;Account&gt; accountsList = [select Id from Account];  for(Account a : accountsList) {     a.Name = 'Test', }  List&lt;Database.SaveResult&gt; res = Database.update(accountsList, false);  for (Database.SaveResult s : res) {     if (!s.isSuccess()) {         system.debug(s.getId()); // I get null here      }  }
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?
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;)
100697
char *strtok(char *s1, const char *s2)      repeated calls to this function break string s1 into "tokens"--that is   the string is broken into substrings,   each terminating with a '\0', where   the '\0' replaces any characters   contained in string s2. The first call   uses the string to be tokenized as s1;   subsequent calls use NULL as the first   argument. A pointer to the beginning   of the current token is returned; NULL   is returned if there are no more   tokens.   Hi,   I have been trying to use strtok just now and found out that if I pass in a char* into s1, I get a segmentation fault. If I pass in a char[], strtok works fine.   Why is this?  I googled around and the reason seems to be something about how char* is read only and char[] is writeable. A more thorough explanation would be much appreciated.
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
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?
7898
The StackExchange app crashes for me on every start when I click a link in the browser. It seems (based on the StackTrace) that the url parser causes a null pointer exception. I'm using 0.1.90.
79598
I wonder if there is a counterpart to java.util.LinkedHashMap in .NET? (ie. the elements are (re)ordered automatically if I access an element. (boolean accessOrder) ).