Reputation: 1
I'm working in Java right now, and I'm attempting to make an array copy itself into a temporary array, and then overwriting again with a new list, however the code isn't functioning.
MobilePhoneInventory.java
public void delete(MobilePhone p) {
MobilePhone[] temp = new MobilePhone[list.length-1];
int adj = 0;
for (int i = 0; i < list.length; i++) {
if (p != list[i]) {
temp[i-adj] = list[i];
}
else adj = 1;
}
list = temp;
numMobilePhone--;
}
MobilePhoneStart.java
if (e.getSource() == myDelete) {
if (inven.size() > 1) {
inven.delete(inven.get(see));
see--;
if (see < 0) {
see = 0;
}
showMP();
} else {
System.exit(0);
}
}
For some reason it's not creating the new list. Any ideas? Thanks in advance.
Upvotes: 0
Views: 104
Reputation: 10268
When copying Java arrays, my preferred way is with System.arrayCopy
. In your case, you have a test inside the loop which actually probably makes your approach more suitable.
Without seeing the rest of your class and how its mutable state works, it's hard to be sure about the solution. Overall, it looks OK. Possibly, there is a mistake with a reference somewhere so you don't get the thing you thought you'd got.
But one thing worth testing is that your equality test is the correct one:
if (p != list[i]) {
because you may find a ! ... .equals
test works more reliably than !=
.
Upvotes: 3