为什么不能在 Java 构造函数中使用字段的速记数组初始化?

发布于 2024-12-18 13:58:05 字数 296 浏览 1 评论 0原文

举个例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

薄暮涼年 2024-12-25 13:58:05

当您在定义行定义数组时,它假设它知道类型是什么,因此 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.

寂寞陪衬 2024-12-25 13:58:05

尝试 list = new int[]{4, 5, 6, 7, 8};

Try list = new int[]{4, 5, 6, 7, 8};.

︶葆Ⅱㄣ 2024-12-25 13:58:05

除了使用 new Object[]{blah, blah....} 这是一种稍微简短的方法来完成您想要的操作。使用下面的方法。

public static Object [] args(Object... vararg) {
    Object[] array = new Object[vararg.length];
    for (int i = 0; i < vararg.length; i++) {
        array[i] = vararg[i];
    }
    return array;
}

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.

public static Object [] args(Object... vararg) {
    Object[] array = new Object[vararg.length];
    for (int i = 0; i < vararg.length; i++) {
        array[i] = vararg[i];
    }
    return array;
}

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文