-1

I am a first term, freshman computer engineering student.

Screenshot of the program

I was watching this HashMap tutorial earlier and was puzzled by the code in the 12th row.

fun.replace("bobbyJoe1996", "b3tt3rP@ssword!")); doesn't in the slightest look like a printable thing to me. Why does the println() method print the former value of the pair in this case?

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
abb
  • 17
  • 4
  • 1
    As you can see from the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#replace-K-V-), `replace` returns a value (the previous value) – ernest_k Feb 02 '20 at 03:20
  • replace(K key, V value) returns the previous value associated with the specified key, in your case Fluffyp0Nies! value for the key getting replaced here i.e. bobbyJoe1996. Also if you observed closely for two sysouts there are two printed lines, first line prints the value getting replaced and second prints map value enclosed in curly braces { } – AK DevCraft Feb 02 '20 at 03:28
  • Please read https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors. Also read [How to ask a good question](https://stackoverflow.com/help/how-to-ask) which makes the same point. – Stephen C Feb 02 '20 at 03:33

1 Answers1

0

Check the HashMap replace method documentation: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#replace-K-V-

It returns the old value, so yes, it is printable. It will print Fluffyp0nies!

It prints the former value because that is what is returned by .replace method, it is designed to work in that way, and it is documented.

Strange that you don't ask for printing the whole HashMap XDDDD, but I will answer that as well: in java nearly everything is printable because every object implements the toString method (see https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--), even if it is the default implementation which returns ClassName@referenceid where referenceid is a hexadecimal code that identifies the object instance.

user1039663
  • 1,230
  • 1
  • 9
  • 15
  • Printing out a HashMap seemed intuitive to me since they are pairs of keys and values. The replace method was very counter intuitive in terms of printing, at least to me. But i get it now thx. – abb Feb 02 '20 at 03:34
  • 1
    General rule for Java programmers: don't rely on your intuition - lookup and read the javadoc. – Stephen C Feb 02 '20 at 03:37