deleting an object from an array - java

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 do 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.

Related

index is out of range, removing item from am array

I'm trying to add the functionality to remove an item from an array via method call but am running into the problem posted in the title.
Heres the instructions:
Write a new method for the ArrayIntList class called remove that takes an integer index and that removes the value at the given index, shifting subsequent values to the left. For example, if a variable called list stores the following values:
[3, 19, 42, 7, -3, 4]
after making this method call:
"list.remove(1);"
would remove 3 from the array (not this is not specific to just the first value of the array
I tried to implement doing this:
public void remove(int index) {
int target = index;
int[] elementDataCopy = new int[size];
size = elementData.length;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("invalid index");
}
//loop through each value until the index given is == to loop value
//create a copy of elementData where length is one less and value at
//index given is not present
//each time something is removed, the tracked values decrease by one
size--;
for(int i = 0; i < elementData.length + 2; i++){
if (elementData[i] == target){
continue;
}else{
elementDataCopy[i] = elementData[i];
}
}
}
``
but get this error:
Failed: Index 12 out of bounds for length 12
with the numbers differing depending on what input is.
note that elementData is an array of ints and index is an int that is pointing at a point in said array
all help is appreciated, pretty sure this is something basic
Try it like this. The big mistake is using i for both source and destination indices. Use a separate one (k here) for destination. Only increment the destination index when the copy is made. Once done,
reassign the elementDataCopy to elementData.
int k = 0;
for(int i = 0; i < elementData.length; i++) {
if (i == index) { // skip the one to "delete"
continue;
}
elementDataCopy[k++] = elementData[i];
}
elementData = elementDataCopy;

Understanding this remove method solution with arrayList [duplicate]

This question already has answers here:
Understanding this removeAll java method with arrayList
(3 answers)
Closed 6 years ago.
This methods duty is to remove all occurrences of the value toRemove from the arrayList. The remaining elements should just be shifted toward the beginning of the list. (the size will not change.) All "extra" elements at the end (however many occurrences of toRemove were in the list) should just be filled with 0. The method has no return value, and if the list has no elements, it should just have no effect.
Cannot use remove() and removeAll() from the ArrayList class.
The method signature is:
public static void removeAll(ArrayList<Integer> list, int toRemove);
The solution:
public static void removeAll(ArrayList<Integer> list, int toRemove) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) = toRemove) {
for (int j = i + 1; j < list.size(); j++) {
list.set(j - 1, list.get(j));
}
list.set(list.size() - 1, 0);
i--;
}
}
I understand the first for loop and the if statement well. Because one would want to iterate through the entire arrayList one-by-one and for each index with a number present in the arrayList check if it is, in fact the toRemovee integer. After this point I become lost.
Why another for loop?
Why are we taking the previous loops variable and adding 1 to it?
why within this second loop are we using the parameters "list" and using a set method?
why j - 1?
why list.get(j)?
Why after this second loop is over is there the line:
list.set(list. sise () - 1, 0) ?
why the i--?
There are a lot of moving parts and I would like to understand the logic.
Thank you
Firstly the if statement is assignment operation which isn't correct. You need to change the = to ==. I have explained each step in the code -
public static void removeAll(ArrayList<Integer> list, int toRemove) {
//start with the first number in the list until the end searching for toRemove's
for (int i = 0; i < list.size(); i++) {
//if the value at i is the one we want to remove then we want to shift
if (list.get(i) == toRemove) {
//start at the index to the right until the end
//for every element we want to shift it the element to its left (i == j - 1)
for (int j = i + 1; j < list.size(); j++) {
//change every value to whatever was to the right of it
//this will overwrite all values starting at the index where we found toRemove
list.set(j - 1, list.get(j));
}
//now that everything is shifted to the left, set the last element to a 0
list.set(list.size() - 1, 0);
//decrement to adjust for the newly shifted elements
// this accounts for the case where we have two toRemoves in a row
i--;
}
}
}
By the end of this function any value that matches toRemove is "removed" by shifting the arraylist to the left everytime the value is found and the last element will be set to 0.
Example
removeAll([1,2,3,4,5,5,6,7,8,5,9,5], 5)
Output
[1,2,3,4,6,7,8,5,9,0,0,0]
Please see the following to learn details (from minute 5:50 or 5:57)
https://www.youtube.com/watch?v=qTdRJLmnhQM
You need the second for loop ,to take all elements after the element you’ve removed it and shift it over one to the left so basically it’s filling up the space that is left empty from removing it so this is what this is doing.

How to shift element in an Arraylist to the right in java

So I am trying to create a method that shifts all of the elements in an arraylist to the right and the last element will become the first element. When I run the code, I am told I have an out of bounds error. Here is what I have so far:
public void shiftRight()
{
//make temp variable to hold last element
int temp = listValues.get(listValues.size()-1);
//make a loop to run through the array list
for(int i = listValues.size()-1; i >= 0; i--)
{
//set the last element to the value of the 2nd to last element
listValues.set(listValues.get(i),listValues.get(i-1));
//set the first element to be the last element
listValues.set(0, temp);
}
}
Maybe this is an exercise you are working on, but the ArrayList.add(int index,E element) method does almost what you want.
"Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices)." (italics added)
So just add the last element in the list at position 0. And delete it from the end.
A few problems here:
Your for loop condition needs to exclude the zeroth element so it should be i > 0 otherwise you'll get to the point where you want to put element at position -1 to position 0 resulting in out of bounds error.
Setting the first element to be the last should be outside the loop.
listValues.set takes in an index in the list as the first parameter, you are giving it the object in the list
public void shiftRight()
{
//make temp variable to hold last element
int temp = listValues.get(listValues.size()-1);
//make a loop to run through the array list
for(int i = listValues.size()-1; i > 0; i--)
{
//set the last element to the value of the 2nd to last element
listValues.set(i,listValues.get(i-1));
}
//set the first element to be the last element
listValues.set(0, temp);
}
The easiest and shortest solution : (if you don't have concurrent use of list - Because in concurrent use and iterating on it, the list size should not change, otherwise you get ConcurrentModificationException)
public void shiftOneToRight() {
listValues.add(0, listValues.remove(listValues.size() - 1));
}
Here is the simplest solution
Collections.rotate(list, rotationPosition);
my code to put a number in the right place in a List
int nr = 5; // just a test number
boolean foundPlace = false;
for(int i = 0; i < integerList.size(); i++){
if(nr <= integerList.get(i)){
integerList.add(i,nr);
foundPlace = true;
break;
}
}
if (!foundPlace)
integerList.add(integerList.size(), nr);
as the guy above said, "integerList.add(element)" inserts the specified element at the specified position in this list. Shifts the element currently...
input array list: locationMap
shift LHS elements from idxStart in circular way
shifted output list: extendedList
// make extended list to behave like circular
List<String> extendedList = new ArrayList<>();
for (int i = idxStart; i < locationMap.size(); i++) { // current to end
extendedList.add(locationMap.get(i));
}
for (int i = 0; i < idxStart; i++) { // 0 to current
extendedList.add(locationMap.get(i));
}

java - referencing elements in an arraylist whilst removing some

I have a for loop looping through each element in an arrayList performing someMethod() on them, depending on the result of that method I either want to keep or remove that element from the list. for example:
int returnResult;
for (int i=0;i<4;i++){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
}
}
My question is; if i have say 5 elements in the list and on the second iteration through the loop (so when i=1), I remove that element, when I go through the 3rd iteration will arrayList.get(2) be referencing what was actually the 4th element? i.e. does it immediately reduce the stack size?
Yes, it does. In order to get around this, you can iterate through the array in reverse.
int returnResult;
for (int i=3;i>=0;i--){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
}
}
This pops them off from the end, and doesn't affect the elements left to go through.
Replace your code with this :
int returnResult, limit = 4;
for (int i=0; i < limit; i++){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
limit--;
}
}

How do I change the order of the items in an arraylist in Java

I have an arraylist. For example
A = [1,2,3,4,5,6,7,8];
I need to change the order of the arraylist so that I can get
A = [2,1,4,3,6,5,8,7]. It means odd position item will be positioned in even positions and vice-versa.
Thanks
A simple approach that assumes
Length of A is given as A.size()
Array A can be accessed by A.get(index) and A.set(index, value)
If your array is not even, the last element is left as-is
Is to swap values in pairs - like this:
for (int index = 1; index < A.size(); index += 2) { // Swap on even indices.
// Swap values at positions index-1 and index.
Object temp = A.get(index-1); // Save value before overwrite.
A.set(index-1, A.get(index)); // First half of swap.
A.set(index, temp); // Final operation for swap.
}
Edit: Changed int to Object, and used A.size, A.get and A.set instead of [] indexers as suggested by comments.
You could do it in the following way:
int a[] = {1,2,3,4,5,6,7,8};
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
for (int i = 0; i < a.length/2; i++) {
int help;
help = a[i*2];
a[i*2]=a[i*2+1];
a[i*2+1] = help;
}
System.out.println("A=["+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+","+a[5]+","+a[6]+","+a[7]+"]");
Ask if you have questions about the code.
Edit: I missed the arraylist, but the principle is the same.

Categories

Resources