Good day,
I have to create a dynamic array class which will represent a string array with dynamic size. I have created the add method and now I have some difficulties with the removeElement method.
Here is my code:
public class DynamicArray {
public String[] dynamicString = new String[0];
public void addElement(String input) {
int loc = findFreeSpace();
if (loc >= 0) {
dynamicString[loc] = input;
}
else {
dynamicString = Arrays.copyOf(dynamicString, dynamicString.length + 1);
dynamicString[dynamicString.length - 1] = input;
}
}
public void removeElement(String input){
for(String eachElement : dynamicString){
if(eachElement.equalsIgnoreCase(input)) ; eachElement = null;
}
}
private int findFreeSpace() {
for (int i = 0; i < dynamicString.length; i++) {
if (dynamicString[i] == null) {
return i;
}
}
return -1;
}
public static void main(String[] args){
DynamicArray array = new DynamicArray();
array.addElement("a");
array.addElement("b");
array.addElement("c");
array.addElement("d");
array.removeElement("a");
System.out.println(array.dynamicString[0]);
}
In the main method 4 String elements are added to the array object. I am using the removeElement method afterwards to remove a particular string element from that object's dynamicString. However, this method fails to work and the system.out.println prints "a" (instead of null) in the console.
;beforeeachElement = null;inif(eachElement.equalsIgnoreCase(input)) ; eachElement = null;(note that this by itself doesn't solve your problem, look at @JBNizet's answer)