-1

sorry I just started learning Java and my question is probably pretty dumb but I would like to get answers.

This is the code that I have written using eclipse ide:

package draft;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Draft {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Map m=new LinkedHashMap();
    String []arr= {"hello","piggie","piggie","piggie"};
    
    for(String x:arr) {
        
    if(m.containsKey(x)) {

    int count=(int) m.get(x);
    m.put(x, count +1);
    }
    else {
    m.put(x,1);
    }
    }
    System.out.println(m);
}
}

So my question is for the code m.put(x,count+1), is this equal to m.put(x,count++). I think they are the same however, Java thinks otherwise... Can someone explain what the difference is in this case? I tried to see what the variables are step by step using debug but after i set the break point and using step into function to figure out how the variables are changing, the variable count just stopped at 1...so i dont know what was going on in that loop...

thank you guys

  • 1
    x + 1 is an expression. x++ increments x by 1 as a side effect AFTER the expression is evaluated. So no not the same. – Nathan Hughes Jan 02 '21 at 03:55
  • Does this answer your question? [Difference in implementation of x = x + 1 and x++](https://stackoverflow.com/questions/19527695/difference-in-implementation-of-x-x-1-and-x) – costaparas Jan 02 '21 at 03:56

1 Answers1

-1

No, it's not the same.

m.put(x, count+1); will put count+1 into m and not increase count while m.put(x, count++); will increase count.

Easy to try :)

jwenting
  • 5,505
  • 2
  • 25
  • 30
  • I dont really get it. I understand that m.put(x, count+1) puts count+1 into m but should not count ++ do the same? my logic for the code: `int count=(int)m.get(x); m.put(x,count++);` is count=the value associated with the key x, then put count++ into key x. According to what you have answered (count++ increases count), then the code `int count=(int)m.get(x)`becomes: increased count=count++ which i have no idea what it means... In other words, I understand how count+1 works and why it works but don't understand why count++ in m.put does not work... if that makes sense... – lilpiggie0522 Jan 03 '21 at 03:37
  • @lilpiggie0522 that's because count++ does the increment only AFTER the put. As I said, just try :) – jwenting Jan 03 '21 at 14:45