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

时间:2012-11-15 18:41:40

标签: 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

4 个答案:

答案 0 :(得分:7)

  • 对于当前调用,您需要var-args constructor 代替。因此,您可以更改constructor声明以获取 var-arg参数: -

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

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

答案 1 :(得分:1)

这应该这样做:  new Temperature(new int [] {1,2,3,4,5,6,7})

答案 2 :(得分:1)

您可以通过以下方式执行此操作

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)
    {
        int [] vals = new int[]{1,2,3,4,5,6,7};  
        Temperature i = new Temperature(vals);
    }




}

答案 3 :(得分:0)

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