简体   繁体   English

如何在 java 中将泛型(Char 或 Integer)变量转换为 int

[英]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). T 可以是 integer 或字符,否则它应该是 output 错误(这是我想要的)。

My method below is trying to convert the argument from char to int or int to int.我下面的方法是尝试将参数从 char 转换为 int 或将 int 转换为 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.如果没有泛型并且 T 是 int 或 char 我没有问题,但由于它没有定义,它不会让我编译。

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 Edit1: {toReturn 而不是 1} 我犯了一个错误并更正了

Edit2: Using the extends Number solution, here are the results that I got Edit2:使用 extends Number 解决方案,这是我得到的结果

    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将参数从 char 转换为 int

I am assuming that you would like to take a numeric character value such as '1' and convert it into an integer.我假设您想取一个数字字符值,例如“1”并将其转换为 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.因此,您必须以某种方式处理异常,以处理char参数不代表数字的情况。 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转换为int以获取字符的 ASCII 值,则只需将char类型转换为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我不知道您为什么要这样做,但它是基于您将char转换为int的简单陈述的替代方案

convert the argument from int to int将参数从 int 转换为 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.由于您使用T作为参数,因此您需要在代码中进行一些检查。

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.尝试使用 instanceof。

  1. If you want to represent any char as it's ASCII code:如果您想将任何字符表示为 ASCII 码:
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:如果您只想处理 char 女巫代表数字并转换为此类数字,而不是 ASCII 码:
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");
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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