+ 1
How to prevent duplicates in a basic way?
public void addMedia(Media media) { if(media == null) { throw new IllegalArgumentException("Media can not be null"); } this.media.add(media); } } How can i use the for each to prevent duplicates?
14 odpowiedzi
+ 2
Secr Now something like this makes my day. Thanks for letting me know.
+ 1
@Avinesh
Omg it worked thank you very much!
+ 1
If you have time then kindly mail me the whole code so that I can go through it and get back to you tomorrow. But what I suggested should have worked for you.
0
Probably try making a HashSet because sets cannot hold duplicates and when you print the values the duplicates won't exist in the result.
0
my Prof. havent taught that yet, so im not allowed to use it.
0
Secr Where are you storing your media objects?
0
public MediaLibrary() {
this.media = new ArrayList<Media>();
}
0
So you are storing everything in an ArrayList. What you can do is probably run a for loop at the end of storing every object and compare every object with every other object and if there is a match then do-
ReferenceVariable.remove(index)
0
Secr if you don't get it then let me see what your final ArrayList looks like so that I can explain you that loop.
0
my Media class is in HTML and the MediaLibrary is in CSS.
https://code.sololearn.com/Wy3T5y12ueLj
0
@Avinesh
public void addMedia(Media media) {
if(media == null) {
throw new IllegalArgumentException("Media can not be null");
}
for(Media currMedia : this.media) {
if(currMedia.getTitle().equals(currMedia.getTitle())) {
this.media.remove(currMedia);
}
}
this.media.add(media);
}
not sure if this one is correct
0
Why is this everywhere, wait I will give you an example.
0
@Avinesh I tried to create a test statement for that but when ever i run the test, the mediaSize() is still 3 instead of 2, since i am removing the duplicate.
@Test
public void testDuplicatesArePreventedFromBeingAdded() {
MediaLibrary mediaLibrary = new MediaLibrary();
Media media1 = new Media("Promare - Inferno", "music", 50);
Media media3 = new Media("Promare - Inferno", "music", 50);
Media media2 = new Media("Overlord", "tv", 52);
mediaLibrary.addMedia(media1);
mediaLibrary.addMedia(media2);
mediaLibrary.addMedia(media3);
assertEquals(2, mediaLibrary.mediaSize(), "checking the number of media in the media list");
assertEquals(media1, mediaLibrary.getMedia().get(0));
assertEquals(media2, mediaLibrary.getMedia().get(1));
}
}