Handout 3.4 - Collections- The Set ADT.pdf

# Handout 3.4 - Collections- The Set ADT.pdf

This preview shows pages 1–3. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Kimani Njoroge. Collections: The Set ADT Page 2 ArrayList<Movie> inventory = new ArrayList<Movie>(); // Add 10 random movies from the list of dvds for (int i=0; i<10; i++) { inventory.add(dvds[(int)(Math.random()*5)]); } for (Movie m: inventory) System.out.println(m); } } Of course, each time that we run this code the result is different. Here is an example of what we may see: Movie: "Bolt" Movie: "The Day the Earth Stood Still" Movie: "Bolt" Movie: "Marley & Me" Movie: "Monsters Vs. Aliens" Movie: "The Day the Earth Stood Still" Movie: "The Day the Earth Stood Still" Movie: "Bolt" Movie: "Bolt" Movie: "Bolt" Can we adjust the for loop so that it only displays unique movies? No. We would have to do some extra work of making a new list with the duplicates removed. So, we could replace the for loop with the following: ArrayList<Movie> uniqueList = new ArrayList<Movie>(); for (Movie m: inventory) { if (!uniqueList.contains(m)) uniqueList.add(m); } for (Movie m: uniqueList) { System.out.println(m); } This would produce the following output (according to the earlier results): Movie: "Bolt" Movie: "The Day the Earth Stood Still" Movie: "Marley & Me" Movie: "Monsters Vs. Aliens" However, there is an easier way to do this. Consider what happens if we change the inventory from an
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern