创建一个接受整数数组的构造函数

bob*_*b t 3 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

给出的错误是:

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
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 7

  • 对于当前调用,您需要var-args constructor 改为.所以,你可以改变你的constructor声明来 var-arg争论: -

    public Temperature(int... a) {
         /**** Rest of the code remains the same ****/
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者,如果你想an array用作参数,那么你需要pass an array像你这样的构造函数 -

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