如何指定常量是字节还是短? [英] How to specify a constant is a byte or short?

查看:95
本文介绍了如何指定常量是字节还是短?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于long数据类型,我可以用L后缀一个数字,以使编译器知道它很长。字节和短字怎么样?

For the long data type, I can suffix a number with L to make the compiler know it is long. How about byte and short?

作为动机,以下产生类型不匹配错误:

As motivation, the following yields a type-mismatch error:

List<Short> a = Arrays.asList(1, 2, 3, 4);


推荐答案

你实际谈论的是一个整数 literal 1 )与长文字 1L )。 Java中实际上没有短文本或字节文字。但通常并不重要,因为存在从整数文字到类型 byte 的隐式转换, short char 。因此:

What you are actually talking about is an integer literal ( 1 ) versus a long literal ( 1L ). There is actually no such thing as a short or byte literal in Java. But it usually doesn't matter, because there is an implicit conversion from integer literals to the types byte, short and char. Thus:

final byte one = 1;  // no typecast required.






隐式转换仅在字面值为在要求的范围内。如果不是你需要一个类型演员;例如。


The implicit conversion is only allowed if the literal is in the required range. If it isn't you need a type cast; e.g.

final byte minusOne = (byte) 255;  // the true range of byte is -128 .. +127

还有其他一些明确的情况需要转换;例如消除方法重载的歧义,或强制表达式中的特定解释。在这种情况下,您需要使用强制转换进行转换。

There are other cases where an explicit conversion is needed; e.g. to disambiguate method overloads, or to force a specific interpretation in an expression. In such cases you need to use a cast to do the conversion.

您的示例是另一种情况。

Your example is another of those cases.

但最重要的是,没有用于表达 byte short的Java语法文字。

But the bottom line is that there is no Java syntax for expressing byte or short literals.

这篇关于如何指定常量是字节还是短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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