在 Java 中设置 char 数组的大小
我正在开发一个 Android 应用程序。
我想将大小设置为像这样的字符数组:
public char[5] language;
但它不起作用。我必须删除第五号才能使其正常工作。
我想将语言变量限制为五个字符。我怎样才能做到这一点?
谢谢。
I'm developing an Android application.
I want to set size to a char array like this:
public char[5] language;
But it doesn't work. I have to delete number five to make it work.
I want to limit to five characters to language variable. How can I do that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能那样做。在 Java 中,数组的类型不包括它的大小。请参阅我对这个早期问题的回答。 (忽略该问题中关于抽象方法的部分......这不是真正的问题。)
数组的大小由创建它的表达式决定;例如,以下创建一个包含 5 个字符的 char 数组,然后将其替换为另一个包含 21 个字符的数组。
请注意,创建是通过 equals 右侧的表达式完成的。数组的长度是其“值”的一部分,而不是其“类型”的一部分。
You cannot do it like that. In Java, the type of an array does not include it's size. See my answer to this earlier question. (Ignore the part about
abstract
methods in that question ... it's not the real issue.)The size of an array is determined by the expression that creates it; e.g. the following creates a char array that contains 5 characters, then later replaces it with another array that contains 21 characters.
Note that the creation is done by the expression on the RHS of the equals. The length of an array is part of its 'value', not its 'type'.
引用 JLS 的话:
要初始化数组,您应该这样做:
其他解决方案是
或
在 Java 中,数组声明不能包含数组的大小;我们只知道该变量将包含特定类型的数组。要初始化数组(并指定大小),您必须使用 new 或使用允许同时初始化和设置数组值的快捷方式来初始化它。
检查数组是否具有指定大小的最佳方法实际上是使用
if(array.length == 5)
之类的内容自己检查数组的大小。资源:
同一主题:
To quote the JLS :
To initialize an array you should do :
Other solutions are
or
In Java, the array declaration can't contain the size of the array; we only know the variable will contain an array of a specific type. To have an array initialized (and with a size) you have to initialize it either by using
new
or by using a shortcut which allows to initialize and set values for an array at the same time.Best way to have to check if an array has a specified size, is actually checking the size of the array yourself with something like
if(array.length == 5)
.Resources :
On the same topic :
变量本身只是 char 数组 (
char[]
) 类型,因此您无法限制变量 type 的大小。您可以限制的是实例化并保存到该变量的数组的大小:The variable itself is just of type char-array (
char[]
), so you can't limit the size of the variable type. What you can limit is the size of the array you instantiate and save to that variable:你不能将变量本身的长度限制为 5;你需要在你的逻辑中强制执行这个不变式。这意味着它也不应该公开:
You can't limit the variable itself to length 5; you need to enforce that invariant in your logic. Which means it also shouldn't be public:
也许您想尝试使用 ArrayList 作为数组的表示形式的通用风格。因此,您可能会发现使用 ArrayList 方法的灵活性。
Maybe you want to try the generic style by using ArrayList as the representation of array. So you may find flexibility using ArrayList methods.