G'day
I have a Java assignment for a introduction course to object oriented programming. I have finished the assignment, and the program works as expected (took me a while to achieve this!) and I get the desired output. Just with one of my methods I have used 2 FOR loops with an IF statement, and I wondering if there is another way that is easier, better or more efficient? But I am not allowed to use an ArrayList. I understand that the ArrayList is easier, better and more efficient, but without being able to use the ArrayList, is it possible to make my code better and still achieve the same result?
Basically I am requesting the user to type an ID number of a property object, then matching that ID to the array index position, copying that object from one array (propertiesForSale) to another array (propertiesSold), adding an increment of 1 to my counter (numPropertiesSold) before deleting and compacting (my teacher said reshuffling) the the first (propertiesForSale) array and decrementing my other counter (numPropertiesForSale) by 1.
My code is as follows..
public void sellProperty(int inID)
{
for (int index = 0; index < numPropertiesForSale; index++) {
if (propertiesForSale[index].getId() == inID) {
propertiesSold[numPropertiesSold]= propertiesForSale[index];
numPropertiesSold++;
for (int i = index; i < numPropertiesForSale; i++) {
propertiesForSale[i] = propertiesForSale[i + 1];
}
numPropertiesForSale--;
}
}
}
If there is an easier, better or more efficient way WITHOUT using an ArrayList, I am just curious to see if there is and how it would be done.
Thanks for your time, patience and input (if any).
If you're not allowed to use ArrayList
that looks to me to be pretty much the best you can do.
Though rather than using a loop to shift the propertiesForSale
array down one you might want to look into using System.arraycopy()
instead of your own loop, since arraycopy()
is a native method.
You could use your own custom linked list made out of nodes. That way you don't need to shift the entries of the array when you sell a property; you just remove the node from the list and update the pointers.
You are searching for inID
in propertiesForSale
. When you find a match you transfer that object to the next index in propertiesSold
and then you compact the array by transferring all records above it to one index lower. The last element is just left there, but it won't be accessed in next lookup because you decrement the count.
Another option is to not compact the array at all, but instead just set it to null. You will of course have to adjust the max bound in the outer for loop and add a non-null check but the inner for loop is gone.
Is it better? Maybe. What you have got is pretty good.
Test your code by filling completely filling the propertiesForSale
array before selling a property. That is, what will happen if numPropertiesForSale == propertiesForSale.length
when you try to remove an element?
if
doesn't loop - Niklas B. 2012-04-05 01:15