arraylist - java - remove elements in list -
arraylist - java - remove elements in list -
help me
movie{ int id; string title; } list<movie> movies = new arraylist<movie>(); film movie1 = new movie(1,"movie1"); film movie2 = new movie(2,"movie2"); film movie3 = new movie(1,"movie3"); film movie4 = new movie(2,"movie4"); movies.add(movie1); movies.add(movie2); movies.add(movie3); movies.add(movie4);
now have list of movies including 4 of above.
(movies1,movies2,movies3,movies4)
but want list of movies contain lastly movies added among ones have same id :
(movies3,movies4);
update : give thanks @leffebrune reply if want 2 or more fields, not one. should do?
movie{ int id; string title ; string plot; } illustration both id , title field. (1,"title1","plot1"),(2,"title2","plot2"),(1,"title3","plot3"),(1,"title1","plot4") become (2,"title2","plot2"),(1,"title3","plot3"),(1,"title1","plot4"),
based on leffebrune's answer, should set whole film object key , override equal method.
you need utilize right info construction this. in case map work:
map<integer, movie> movies = new hashmap<>(); film movie1 = new movie(1,"movie1"); film movie2 = new movie(2,"movie2"); film movie3 = new movie(1,"movie3"); film movie4 = new movie(2,"movie4"); movies.put(movie1.id, movie1); movies.put(movie2.id, movie2); movies.put(movie3.id, movie3); movies.put(movie4.id, movie4);
now map contains { movie3, movie4 } or lastly added movies id.
if want utilize "composite keys" integer id , title identify film need either utilize more complicated info construction or resort hacks. 1 easy way create composite key concatenate fields in string , utilize string key in map:
import java.util.hashmap; import java.util.map; class movies { static class film { int id; string title; string plot; movie(int id, string title, string plot) { this.id = id; this.title = title; this.plot = plot; } @override public string tostring() { homecoming string.format("{ %d, %s => %s }", id, title, plot); } } public static void main(string[] args) { map<string, movie> movies = new hashmap<>(); film movie1 = new movie(1, "title1" ,"plot1"); film movie2 = new movie(2, "title2", "plot2"); film movie3 = new movie(1, "title3", "plot3"); film movie4 = new movie(1, "title1", "plot4"); // create composite key combining id , title string. movies.put(movie1.id + movie1.title, movie1); movies.put(movie2.id + movie2.title, movie2); movies.put(movie3.id + movie3.title, movie3); movies.put(movie4.id + movie4.title, movie4); (map.entry<string, movie> entry : movies.entryset()) { system.out.printf( "key: %s value: %s%n", entry.getkey(), entry.getvalue()); } } }
the proper way implement such key require creating object , overriding equals , hashcode methods. way more advanced territory.
java arraylist
Comments
Post a Comment