java - 制作一个接受整数数组的构造函数

标签 java arrays constructor

如何将整数数组传递到我的构造函数中?

这是我的代码:

import java.io.*;
import java.util.*;

public class Temperature implements Serializable
{
    private int[] temps = new int [7];
    public Temperature(int[] a)
    {
        for(int i=0; i < 7; i++)
        {
            temps[i] = a[i];
        }

    }
    public static void main(String[] args)
    {
        Temperature i = new Temperature(1,2,3,4,5,6,7);
    }
}

给出的错误是:

Temperature.java:17: error: constructor Temperature in class Temperature cannot be applied to given types;
        Temperature i = new Temperature(1,2,3,4,5,6,7);
                        ^
  required: int[]
  found: int,int,int,int,int,int,int
  reason: actual and formal argument lists differ in length
1 error

最佳答案

  • 对于当前调用,您需要一个var-args 构造函数 反而。因此,您可以更改 constructor 声明以采用 var-arg 参数:-

    public Temperature(int... a) {
         /**** Rest of the code remains the same ****/
    }
    
  • 或者,如果您想使用一个数组作为参数,那么您需要传递一个 array 像这样给你的构造函数 -

    Temperature i = new Temperature(new int[] {1,2,3,4,5,6,7}); 
    

关于java - 制作一个接受整数数组的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404029/

相关文章:

PHP从数组插入sql

c - 在c中初始化指针数组

jQuery 在图像 slider 更改时更改 href

c++ - error C2248,这是什么错误,我该如何解决?

java - 使用 maven jetty 插件在 java 8 上运行 jetty 9 时获取错误扫描文件

java - jersey-test-framework grizzly 返回 404 未找到错误

java - 我们可以说非静态 block 作为类的构造函数吗?

java - 实现特定接口(interface)的类的集合

Java无法正确计算点到线的距离

java - Hazelcast:管理中心不工作