Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Guaranteeing an Array size passed to an object or method

Status
Not open for further replies.

Haazi2

Programmer
Aug 25, 2000
51
US
I have the following code:

// test program
public class Array
{
private final static int ROW = 3;
private final static int COL = 3;
private static String[][] weStatementLines = ;

public Array(String[][] weStatementLines)
{
this.weStatementLines = weStatementLines;
}

public String[][] getArray()
{
return weStatementLines;
}

public void setArray()
{
this.weStatementLines = weStatementLines;
}
}

// test program
public class TestArray
{
public static void main(String[] arg)
{
String[][] size = { {"me"}, {"this"}, {"it"}, {"456"}, {"then"} };
Array New = new Array(size);
String[][] One = New.getArray();
System.out.println("array size = " + One.length);
for (int i = 0; i < One.length; i++)
{
System.out.println(One);
}
}
}

I'm trying to guarantee that when an Array object is created that the only valid Array that will be accepted will be a 3x3 array. How would I do this? I could check the array used to instantiate the class and throw an exception but is this the better way to do it? Thanks for any help in advance.
 
hi

yes throwing an exception is the best solution

and the only way the constructor can inform you that it can't construct the object...

but you better use the 'clone' method inherited from the class 'Object' to copy the String[][] that you pass to the constructor because a change made to it outside the Array object will also affect the String[][] inside the Array object, changing then its side...

manu0
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top