简体   繁体   中英

Updating ArrayLists that contains each other?

Apologies if there have been similar questions, I'm honestly not sure how to call this concept to search for questions.

So I need to create a database with 3 classes like below:

public class Actor {
    private String name;
    private ArrayList<Movie> movies; //all movies the actor has been in
}

public class Movie {
    private String name;
    private ArrayList<Actor> actors;
}

public class MovieDatabase {
    private ArrayList<Movie> movieList;
    private ArrayList<Actor> actorList; //all actors in the movie
}

I have to create a method to add a movie and an actor to the database. The final goals is that the new movie needs to be of the Movie class, and contains all the actors that are in it, same for the new actor.

What I cannot figure out is that, since the Movie class contains an array of Actor objects, and the Actor class contains an array of Movie list, how do you update so that in the end, the new Movie added contains a complete list of Actors in it, with each Actor in the list having their movie lists updated with the new Movie object?

Is recursion the right concept to apply in this case?

Suppose a new Movie gets added

Movie movie = new Movies();

movie.setActors(listOfActors)

Now for each actor you need to update the movie list

listOfActors.forEach(actor -> addMovieToActor(movie,actor));


public addMovieToActor(Movie movie,Actor actor){

   List<Movies> existingMovies =actor.getMovies();

   existingMovies.add(movie);
}

Depending on your needs, you may need to take care of synchronization between updates.

I don't think recursion is appropriate here, although you could use it. The databases have a circular dependency so you just need to synchronize after updates. In other words, make sure that after you add a new entry, both databases are updated with the missing information. Synchronization can be made easier by swapping ArrayList out for a HashMap , you may need to refactor your classes to do this. I left out the lists for simplicity, you can add them in as a parameter:

void update(String movieName, String actorName) {
    if (movies.get(movieName) == null) {
        movies.put(movieName);
    } 
    if (actors.get(actorName) == null) {
        actors.put(actorName);
    }
}

Use as:

HashMap<String> actors = new HashMap<>();
HashMap<String> movies = new HashMap<>();
actors.put("foo");
movies.put("bar");
// Update happened, synchronize with what you just added
update("foo", "bar");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM