Reputation: 85
static String[] Student = new String[6]; //My array
First I need to add a list of elements to this array. Then remove a specific element from the array. After that add another element to the array.
Can I do these three without creating another new array?
Upvotes: 2
Views: 557
Reputation: 584
The answer is yes and no. Technically you can accomplish this with a Java array - as Java arrays are not immutable, but you shouldn't - there are other data structures better suited to this.
Here's how you would do it with an array:
public static void main(String[] args)
{
String[] bad = {"a","b","c","d","e","f"};
removeAndAdd(bad, 2, "g");
}
private static void removeAndAdd(String[] arr, int indexOfDel, String toAdd){
removeElement(arr, 2);
arr[arr.length-1] = toAdd;
}
private static void removeElement(String[] arr, int index){
for(int i = index; i < arr.length; i++){
arr[i] = null;
if(i+1 < arr.length) arr[i] = arr[i+1];
}
}
The problem with this code is that depending on what you want the collection for, there are simpler ways to do this or ways to do this with better runtimes.
Runtime - The runtime of the above code is o(n). This is because if you delete an element at the front of the array, then you need to move all of the elements in the array 1 place over - i.e. an operation that is based linearly on the number of elements. There are other collections that provide different better runtimes for deletion but have other tradeoffs. See this website that lists the runtimes for delete for different data structures.
Simplicity - Another reason to avoid using an array for this is that you can have the same functionality with the same runtime but have the functionality built-in for you if you use something like an ArrayList.
ArrayList<String> good = new ArrayList<>(Arrays.asList(new String[]{"a","b","c","d","e","f"}));
good.remove(2);
good.add("g");
In this example, you accomplish the same exact result but you have to write far less code.
See also this article that compares Java arrays vs arraylists.
Upvotes: 3