array
is not data structure when you plan to remove an items, because to do so you have to create another array
and copy all other items. Check this out:
static class Movie {
private final String id;
public Movie(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
public static Movie[] deleteMovieById(Movie[] movies, String id) {
int pos = findMovieById(movies, id);
if (pos == -1)
return movies; // not found; retrieve source array
Movie[] arr = new Movie[movies.length - 1];
System.arraycopy(movies, 0, arr, 0, pos);
System.arraycopy(movies, pos + 1, arr, pos, arr.length - pos);
return arr;
}
private static int findMovieById(Movie[] movies, String id) {
for (int i = 0; i < movies.length; i++)
if (movies[i].getId().equals(id))
return i;
return -1;
}
Output:
Movie[] movies = {
new Movie("1"),
new Movie("2"),
new Movie("3") };
Movie[] res = deleteMovieById(movies, "1");
Correct data structure to hold and to remove with constant time
element is Map
:
public static void deleteMovieById(Map<String, Movie> movies, String id) {
movies.remove(id);
}
Output:
Map<String, Movie> movies = Map.of(
"1", new Movie("1"),
"2", new Movie("2"),
"3", new Movie("3"));
deleteMovieById(movies, "1");
Can you see the difference?!