简体   繁体   中英

Cast from Integer to Character without using unsafe conversion

I have to write a method that has a parameter of type Integer and has to return an object of type Character. If the value of the given parameter is presentable as a Character object, Return it as a Character. Else return null.

My task is poorly formulated it says: "Unsafe conversions (eg from int to char) are not allowed in your code" I suppose it is not unsafe but also not allowed somehow?

My Code so far:

public Character methodName (Integer i) {

        if (i >= 0 && i <= Character.MAX_VALUE) {
            return Character.valueOf((char) i.intValue());   //unsafe conversion
        }
        else
            return null;
    }

I tried fixing it by any means but just could not come up with an solution not using the unsafe conversion, thank you very much in advance for helping!

Solution to this weird formulated task:

public Character methodName (Integer i) {

        if (i >= 0 && i <= Character.MAX_VALUE) {
            return (Character.toChars(i)[0]); //<- solution
        }
        else
            return null;
    } 

Your conversion is safe here.

  • You're checking if the int is in the Character range
  • Then you cast using a builtin method

There might be another way but it's trickier and weird:

String iStr = Integer.toString(i.intValue())
char c = iStr.charAt(0)
Character crt = Character.valueOf(c)

I repeat myself but your approach is more than fine... I don't understand what does your teacher expect from you.

To my mind

  if (i >= 0 && i <= Character.MAX_VALUE) {
       return Character.valueOf((char) i.intValue());
  }

is completely safe according to your teacher's definition of "safe".

SO my teacher said it is indeed unsafe, because the value range of int is 2^32 and of char is 2^16.

The if test ensures that you only cast i.intValue() to a char when i is in the required (safe) range.

The flipside is that if a provably correct range check is not sufficient to make this "safe" enough for your teacher, then AFAIK there isn't a "safe" solution. All other less direct solutions also entail an explicit or implicit range check in some form... and will therefore also be "unsafe".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM