简体   繁体   English

Integer.valueOf 针对一个字符返回 ASCII

[英]Integer.valueOf returns ASCII against a character

Integer.valueOf takes in String and int as arguments but when I pass Character , it doesn't require casting and compiler doesn't enforce anything. Integer.valueOf接受Stringint作为参数,但是当我传递Character ,它不需要强制转换并且编译器不强制执行任何操作。

Character doesn't extend String class, it just implements Serializable and Comparable Character 不扩展String类,它只是实现了SerializableComparable

Character charc = '1';
System.out.println(Integer.valueOf(charc));
System.out.println(Integer.valueOf(charc.toString()));

output:输出:

49
1

Isn't it kind of design flaw or I am thinking in the wrong direction?这不是设计缺陷还是我在错误的方向思考? Please write the reason in comments when you down-vote it.当您拒绝投票时,请在评论中写下原因。

在此处输入图片说明

This is specifically covered by JLS 5.2, Assignment conversion . JLS 5.2, 分配转换专门涵盖了这一点。 (Passing a parameter to a method is essentially like assigning a value to a variable.) (将参数传递给方法本质上就像为变量赋值。)

Assignment contexts allow the use of one of the following:赋值上下文允许使用以下之一:

... ...

  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.一个拆箱转换(第 5.1.8 节),可选地后跟一个扩大的原始转换。

What's happening here is that the Character is being unboxed to char ;这里发生的事情是Character被拆箱为char and then the char is being widened to int .然后char被扩大到int

The char ist auto-widened to an int, which is a perfectly valid parameter for Integer.valueOf() char ist 自动扩展为 int,这是Integer.valueOf()一个完全有效的参数

Java converts some types automatically if the required type contains all of the current type like char to int or int to long.如果所需类型包含所有当前类型,如 char 到 int 或 int 到 long,Java 会自动转换某些类型。 See the Java Language Specification for details.有关详细信息,请参阅Java 语言规范

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

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