Jose Lopez Jose Lopez - 21 days ago 8
Java Question

Error converting Optional<String> to Integer from TextInputDialog

In this example I have tempSocket1 and tempSocket2 but I really just want one of them. I just included both to show I tried both methods, but I keep getting an error, "the method valueOf(String) in the type Integer is not applicable for the arguments (Optional)." I thought both of these methods were the ones used for converting a string data type to integer, but I'm not sure how the Optional part changes the whole system.

private void showTextInputDialog() {
TextInputDialog changePort = new TextInputDialog("Settings");
changePort.setHeaderText("Change Port");
changePort.setContentText("Please enter port number to be used for establishing connection...");

Optional<String> result = changePort.showAndWait();
result.ifPresent(e -> {
Integer tempSocket1 = Integer.valueOf(result);
Integer tempSocket2 = Integer.parseInt(result);
}
);
}

Answer

You see, Integer.valueOf and Integer.parseInt methods need an argument of type String, but you are passing an Optional<String>. So that's why the error occurred. Optional string and string are not the same.

Just think about this, if Optional<String> were the same as String, would ArrayList<String> be the same as String? Would LinkedList<String> be the same as String? What about HashMap<String, Integer>? Would it be both a String and an Integer?

The chaos that treating generic types the same as their generic type arguments would bring is destructive! Imagine calling charAt on an optional string! Without the implementation, no one knows what will happen...

So yeah, never think that generic types are the same types as the generic type parameters.