为什么要在Java中将字符从char显式转换为int?
我在Java代码的很多地方都看到过,人们倾向于在基元int和char之间进行转换。
I have seen in Java code in many places, people tend to cast between primitives int and char.
这有必要吗?它们不是隐式转换的吗?
例如我尝试了一下,完全得到了我应该做的。那为什么人们要明确地投身呢?我错过了什么吗?
Is this necessary? Are they not implicitly converted.
For e.g. I tried this and exactly got what I should. Then why do people explicitly cast? Am I missing something?
char a = 'a';
int index = (int) a;
index = 98;
a = 98;
System.out.println(index);
System.out.println(a);
有时候人们会为清楚起见,有时出于重载的原因,有时是出于无知的原因。
Sometimes people will cast for clarity, sometimes for overloading reasons, and sometimes for reasons of ignorance.
例如:
System.out.println((int) a);
的工作方式与
System.out.println(a);
由于过载解析。但是,按照您提供的确切代码,绝对不是必需的。如果您想确切地知道为什么某个特定的开发人员选择编写冗余代码,则需要询问他们...
due to overload resolution. But in the exact code you've given, it's definitely not required. If you want to know exactly why a particular developer has chosen to write redundant code, you'd need to ask them...