Lab: Practicing with Collections
IDE Setup
Before starting this lab, make sure you have completed the setup instructions in the CS240 Setup instructions.
Starter Files
Download the following starter files for this lab:
- CollectionExercises.java - starter code
- CollectionExercisesTest.java - contains the Gradescope test cases
Important: Package Declaration
The files have the package declaration package labs.collections;. This means that the files should be placed in a directory named collections inside a directory named labs inside your source/project directory.
For example, if your source/project directory is src, you should have a directory structure like this:
src/
├── labs/
│ └── collections/
│ ├── CollectionExercises.java
│ └── CollectionExercisesTest.java
If you don't have a labs directory, you should create it. If you don't have a collections directory, you should create it.
Instructions
Your goal in this lab is to complete the unfinished methods in CollectionExercises.java.
Your solutions for these exercises must satisfy the following requirements:
- You may not use indexed for loops. Use only for-each loops or iterators, as appropriate.
- None of your methods may include nested loops. Nested loops generally take a long time to iterate over large collections.
- You must follow the style guidelines for this lab! Typically, labs will not require style, but we want to make sure you have set up your IDE correctly.
Read the hints below carefully before starting the exercises!
Hints
-
For some methods, you should create a new collection object to help you solve the problem. For instance,
containsDuplicatescan be solved by using aHashSet. -
You can create a collection that contains all elements from another collection:
- Using a constructor:
HashSet<Integer> = new HashSet<>(other); - Using the
addAllmethod.
- Using a constructor:
Solutions
If you're stuck, learn from the first two solutions:
removeSmallInts
public static void removeSmallInts(List<Integer> list, int minVal) {
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
int val = iter.next();
if (val < minVal) {
iter.remove(); // Remember, only the iterator can remove elements while looping.
}
}
}
containsDuplicates
public static boolean containsDuplicates(Collection<Integer> ints) {
// Sets are unique, so if it contains fewer elements, there must have been duplicates.
HashSet<Integer> set = new HashSet<>(ints);
return set.size() < ints.size();
}
Submitting
You will submit your completed file through Gradescope. You may submit as many times as you like.