Differences between using Typecast and wrapper class?

Asked

Viewed 74 times

0

Hello, the activity proposal would show how old the user would be, I wrote my code first to then be able to compare with the teacher, it turns out that my first line came out much smaller than the teacher’s.

This is my code:

int an = (int) txtAN.getValue();    // an (ano de nascimento), pega o valor de um spinner
int ran = 2017 - an;    // ran (resultado do ano de nascimento)
lblIdade.setText(Integer.toString(ran));    // mostra no label o valor recebido

This is the teacher’s:

int an = Integer.parseInt(txtAN.getValue().toString());
int id = 2017 - an;
lblIdade.setText(Inteer.toString(id));
  1. What are the pros and cons of using the typecast (as in mine case), or use the wrapper class (as in the case of the teacher)?
  2. Which method is "correct" or "wrong"? Why?

Note: It is a project using Swing.

  • 2

    In the end, both will turn int or cast exception if it is not possible, I see no difference. Alias, in my opinion, neither of the two forms is "correct", the recommended, since it is a numerical spinner, is pass a Spinnernumbermodel, which dispenses any cast to integer when redeeming getvalue.

  • Could you make an example of how to use Spinnernumbermodel? I don’t understand.

  • 1

    In fact the two are wrong, even if you did it this way, you would have to treat the exception, which I find horrible, but Java prefers to do horrible things, so it’s the only option if you really want to receive text.

  • So would I really have to use Spinnernumbermodel? That’s what you meant?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.