I am trying to create a instance of the object Iset. When the person makes the object they have to give an int which will be the size of a boolean array that will store a set of
size
variable in your constructor is a local variable, that's why other member methods doesn't get the right size to check.
Assign the value to this.size
, then it will work:
ISet(int a) {
this.size = a;
seti = new boolean[size];
You should use the this
keyword, an make the constructor public if you want to instantiate it in another class:
public class ISet {
public int size;
boolean[] iSet;
public ISet(int a) {
this.size = a;
this.iSet = new boolean[a];
}
You are creating a new variable inside your constructor and this is called shadowing. Use this
to set the attributes of the current object:
this.size = a;
You're creating a new int
variable inside the constructor. Instead, you just need to do this.size = a;
in the constructor.
You are not initializing the size instance variable properly, instead you are initializing a local variable size. Therefore your size instance variable remained initialized with 0 and your seti instance variable is an empty array causing the out of range error.
As pointed out by others, you don't need the instance variable size.
There is also no need for another local variable size inside your constructor, Just use seti.length to determine the size of the array. To simplify, your code should be:
public class Iset {
boolean[] seti;
ISet(int a) {
seti = new boolean[a];
I would recommend you use static analysis tools like checkstyle to eliminate bug like this in your codes.
Lets have a look at your code :
public class Iset {
public int size;// Declares a Member of a class and all the objects will have a copy of this member
boolean[] Iset;
.....
}
ISet(int a) {
int size = a; //This line is declaring a **local variable** called size
seti = new boolean[size];
...
}
See in your constructor you've created a local variable size
but you also have a class member called size
in your class. So in this scenario whenever we try to set size
variable within constructor, there arises a conflict to the compiler whether to set the local variable or the class member ( this conflict is because of the fact that both the local variable and class member has same name ) . In such scenarios the compiler chooses local variable size over the class member size. But for you to make sure that the values you use in the constructor are used in all of my methods, you have to set the class member. To set the class member we use following code:
this.size = a;//Says set the object member size to value present in a.
Here we refer the size using this pointer because we need to set the object's size variable and not the local variable size.