简体   繁体   中英

how do you convert a generic(Char or Integer) variable into an int in java

T can be either an integer or a char otherwise it should output an error(which is what i want).

My method below is trying to convert the argument from char to int or int to int.

I have no problem if there is no generic and T was int or char but since its not defined, it wont let me compile.

Is there any way to bypass this, or is there another way of converting a generic variable?

Current Code gives error:

incompatible types: T cannot be converted to int
        int toReturn = gKey;
public class MyClass<T>{
    private int convert(T gKey){
        int toReturn = gKey;
        return toReturn;
    }
}

Edit1: {toReturn instead of 1} I made a mistake and corrected

Edit2: Using the extends Number solution, here are the results that I got

    public static void main(String[] args) {
        //test 1 for integer argument, should output 1:: success
        Test<Integer> test1 = new Test<>();
        int a = 1;
        System.out.println(test1.convert(a));
        //test 2 for character argument, should output 65 :: failure compile error
        Test<Character> test2 = new Test<>();
        char b = 'A';
        System.out.println(test2.convert(b));
    }

convert the argument from char to int

I am assuming that you would like to take a numeric character value such as '1' and convert it into an integer. If so, that's done simply like this:

char c = '1';
int i = Integer.parseInt(String.valueOf(c));

Of course, this conversion only work for numeric characters. Therefore, you must handle exception in some way to deal with cases when the char parameter does not represent a number. For example:

try {
    int i = Integer.parseInt(String.valueOf(c));
} catch (NumberFormatException nfe) {
    // do something here
}

On the other hand, if your intent is to "convert" a char into an int to get the ASCII value of the character, all you need is to typecast the char into an int :

char c = 'a';
int i = (int) c; // i should be 97 decimal (61 hex)

I don't know why you would want that, but it is an alternative based on the plain statement you made of "converting" a char to an int

convert the argument from int to int

This should be simply returning the argument. There is no "conversion" required.

The solution

Since you're using a T as an argument, you need to do some checks in in the code.

if (arg instanceof Character)
    return Integer.parseInt(String.valueOf((char)arg));
if (arg instanceof Integer)
    return (int) arg;
// for all other cases, either throw exception (i.e. `IllegalArgumentException`) or return some erroneous value (i.e. if the expected return value is zero or greater, you could return -1)

Try use instanceof.

  1. If you want to represent any char as it's ASCII code:
private int convert(T gKey) {
 if (gKey instanceof Integer)
    return ((Integer) gKey).intValue();
 else 
   if (gKey instanceof Character)
      return ((Character) gKey).charValue();
   else throw new IllegalArgumentException("IllegalArgumentException");
}
  1. If you want to process only char witch represents number and convert to such number, not to ASCII code:
private int convert(T gKey) {
  if (gKey instanceof Integer)
     return ((Integer) gKey).intValue();
  else 
    if (gKey instanceof Character)
       try {
            return Integer.parseInt(Character.toString((Character) gKey));
           }
       catch (NumberFormatException e) {
             throw new NumberFormatException ("NumberFormatException ");
           }          
    else throw new IllegalArgumentException("IllegalArgumentException");
} 

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