为什么要在Java中将字符从char显式转换为int? [英] Reason to explicitly cast from char to int in Java?

查看:106
本文介绍了为什么要在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...

这篇关于为什么要在Java中将字符从char显式转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆