为什么不能在 Java 构造函数中使用字段的速记数组初始化?
举个例子:
private int[] list;
public Listing() {
// Why can't I do this?
list = {4, 5, 6, 7, 8};
// I have to do this:
int[] contents = {4, 5, 6, 7, 8};
list = contents;
}
为什么我不能使用简写初始化?我能想到解决这个问题的唯一方法是创建另一个数组并将 list
设置为该数组。
Take the following example:
private int[] list;
public Listing() {
// Why can't I do this?
list = {4, 5, 6, 7, 8};
// I have to do this:
int[] contents = {4, 5, 6, 7, 8};
list = contents;
}
Why can't I use shorthand initialization? The only way I can think of getting around this is making another array and setting list
to that array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在定义行定义数组时,它假设它知道类型是什么,因此 new int[] 是多余的。但是,当您使用赋值时,它并不假设它知道数组的类型,因此您必须指定它。
当然,其他语言对此没有问题,但在 Java 中,区别在于您是否在同一行定义和初始化字段/变量。
When you define the array on the definition line, it assumes it know what the type will be so the
new int[]
is redundant. However when you use assignment it doesn't assume it know the type of the array so you have specify it.Certainly other languages don't have a problem with this, but in Java the difference is whether you are defining and initialising the fields/variable on the same line.
尝试
list = new int[]{4, 5, 6, 7, 8};
。Try
list = new int[]{4, 5, 6, 7, 8};
.除了使用
new Object[]{blah, blah....}
这是一种稍微简短的方法来完成您想要的操作。使用下面的方法。PS - Java 很好,但在这些情况下它很糟糕。如果可能的话,在您的项目中尝试使用 ruby 或 python有理有据。 (看看 java 8 仍然没有简写用于填充哈希图和他们花了这么长时间才做出一个小改变来提高开发人员的生产力)
Besides using
new Object[]{blah, blah....}
Here is a slightly shorter approach to do what you want. Use the method below.PS - Java is good, but it sucks in situations like these. Try ruby or python for your project if possible & justifiable. (Look java 8 still has no shorthand for populating a hashmap, and it took them so long to make a small change to improve developer productivity)