I have an array of objects of my custom class and i want to delete a random object(chosen by some criteria). how do i d开发者_开发问答o this and keep the array ordered? naturally, there would be shifting of elements towards the left but i don't quite get the deleting the element part and need help formulating the logic. this is what i am doing but for it doesn't work correctly :(
public static void deleteRecord(Customer[] records, int AccId){
int pos=0; // index
boolean found = false;
for (int i=0; i<count; i++){ // count is the number of elements in the array
if (records[i].get_accountid()==AccId){
found = true;
pos = i;
break;
}
}
if (!found)
System.out.println("The Record doesn't exist");
for (int j=pos+1; j<count; j++) {
records[j-1]= records[j];
}
You can just shift the elements to the left as this will overwrite the item to be deleted.
public void remove(Object[] a, int index) {
for (int i = index + 1; i < a.length && a[i] != null; i++) {
a[i - 1] = a[i];
}
}
Assuming that the first null
indicates the end of the elements.
Of course, this is O(n) time and there are data structures like LinkedList that can remove elements in O(1) time.
Unfortunately, you can't just delete an element from an array, not without either leaving empty indices or creating a new array. I would create a new array and use System.arraycopy to simplify copying over your elements. Something like:
Object[] newArr = new Object[arr.length-1];
System.arraycopy(arr,0,newArr,0,index);
System.arraycopy(arr,index+1, newArr, index, newArr.length - index);
return newArr;
Where arr
is your original array and index
is the random index to remove. Basically, it copies all elements up to the index to remove, and then copies all elements after the index. You can wrap this up in a separate method for simplicity. (Instead of using arraycopy
, you could use two for-loops to accomplish the same thing).
I strongly suggest as others have to use a List, which simplifies adding and removing elements.
use List collection e.g:
List<String> list = new ArrayList<String>();
int toDelete = getRandomIndex(lst.size()); //your own implementation
if (toDelete >= 0) {
list.remove(toDelete); // it'll remove and shift elements
}
documentation about List.remove(int):
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
精彩评论