Quick programming form question..

Ok.. So I have a method that returns an array of BigIntegers.. What I get in this method is an array of unknown length, until it is passed of course. So, I create an array to store my data in (I'm determining which BigIntegers are odd in this case...) not knowing how long it needs to be.. since I have no idea how many odds are in the array until I check. So, what I did was to use a for each loop instead of a for loop with a counter that I then used to construct a new array of a proper size for the odds and then stuck all the data from the temp array into this new array. Is this bad coding practice?

Heres the code because I don't think I'm eloquent enough to get that across right...

public BigInteger[] getOdds(BigInteger[] Integers)

{

BigInteger[] temp =new BigInteger[Integers.length];

int x = 0;

for(BigInteger On : Integers)

{

if(On.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO) != 0)

{

temp[x] = On;

x++;

}

}

BigInteger[] output =new BigInteger[x];

for(int i = 0; i < x; i++)

output[i] = temp[i];

return output;

}

[1618 byte] By [popupmana] at [2007-11-27 2:09:21]
# 1
Use a List and convert it to an array at the end (or return the list).
-Kayaman-a at 2007-7-12 1:59:40 > top of Java-index,Java Essentials,Java Programming...
# 2
Use an ArrayList instead, and call toArray(new BigInteger[size]) when you want to convert back to an array.Kaj
kajbja at 2007-7-12 1:59:40 > top of Java-index,Java Essentials,Java Programming...
# 3

I agree you should be using an ArrayList as it does just this.

To answer your question I wouldn't create a new array at the end as this is very inefficient. Instead I would pass the over sized array back and only iterate it until I hit a marker (could be a null object) which would indicate the end has been reached.

Take a look at the source code for ArrayList.

ChristopherAngela at 2007-7-12 1:59:40 > top of Java-index,Java Essentials,Java Programming...
# 4

Thank you for the quick reply's. My teacher insisted that I not use an ArrayList as that would make it too easy.. I would have preferred that because it makes things so simple with a nice easy ArrayList<BigInteger>... but thanks for the tips. And as to the putting in of a stop mark instead, thanks for the suggestion. Maybe that explains the loss of points on this program. Once again, thanks for the quick reply's and the useful suggestions.

popupmana at 2007-7-12 1:59:40 > top of Java-index,Java Essentials,Java Programming...