Java中数组的构造函数

问题描述:

我正在处理一个问题,我需要一个由布尔数组表示的类。这是我唯一的构造函数。Java中数组的构造函数

private boolean[] integerSet; 
private static final int ARRAY_LENGTH = 101; // set will always be 0-100 

// no argument constructor 
// creates set filled with default value false 
public Exercise_8_13() 
{ 
    integerSet = new boolean[ARRAY_LENGTH]; 
} 

我毕竟这写的方法给出了错误“类型的表达式必须是一个数组类型,但它决心Exercise_8_13”。这些方法正在采用Exercise_8_13类型的参数。

我是否需要制造另一种类型的构造函数来防止错误?或者它是我在构造函数中的东西?该问题仅指定必须创建无参数构造函数。

我看过这个问题,这似乎是一个类似的问题,但我仍然不明白的解决方案。 The type of an expression must be an array type, but it is resolved to Object

这是一个示例方法,在[counter],b [counter]和intersectionSet [counter]两个实例上触发错误。

public static void intersection(Exercise_8_13 a, Exercise_8_13 b) 
    { 
      Exercise_8_13 intersectionSet = new Exercise_8_13(); 
      for (int counter = 0; counter < ARRAY_LENGTH; counter++) 
      { 
        if ((a[counter] = false) || (b[counter = false])) 
        { 
        intersectionSet[counter] = false; 
        } 
        else 
        { 
        intersectionSet[counter] = true; 
        } 
      } 
    } 
+7

向我们展示你正在谈论的方法... – arshajii 2013-04-27 23:04:44

+0

我写的方法之后,所有提供的错误“表达式的类型必须是一个数组类型 duffy356 2013-04-27 23:35:02

+2

我加了这个方法,对不起! – 2013-04-28 00:25:15

你被写a[counter],即使a治疗aboolean阵列Exercise_8_13型的,而不是boolean[]类型。你正在做同样的bintersectionSet

你想检查integerSet[counter]a,所以改变a[counter]a.integerSet[counter]

b[counter]intersectionSet[counter]一样。

+1

非常感谢,这个回复真的帮助我理解。 – 2013-04-28 00:48:52

我不是很清楚为什么你会得到错误,但我试图运行我的代码版本,它工作正常。首先,构造函数仅在创建类的实例时运行。因此,如果您在主要方法中创建相同的实例并检查数组的长度。这是运行良好的代码。

public class Exercise_8_13{ 

private static boolean[] integerSet ; 
private static final int ARRAY_LENGTH = 101; 

public Exercise_8_13() 
{ 
    integerSet =new boolean[ARRAY_LENGTH]; 
} 
public static void main(String args[]) 
{ 
    Exercise_8_13 z = new Exercise_8_13();//new instance being created 
    if(integerSet!=null) 
    { 
     System.out.println("Success " +integerSet.length); 
    } 
} 
} 

你的构造函数很好。您的错误表明预期类型与您试图在其中一种方法中接受或返回的类型之间不匹配。如果您共享出现错误情况的方法之一,那么很容易发现它。例如,如果你有一个看起来像这样的方法,那么你的编译器会认识到所声明的返回类型(Exercise_8_13)和实际返回类型(boolean [])之间的不匹配。

public Exercise_8_13 copy() { 
    return this.integerSet; // deliberate bug 
} 
+0

在一个不相关的注释中,名字“integerSet”对描述布尔值数组的东西有点不同寻常 – phatfingers 2013-04-27 23:41:12