0% found this document useful (0 votes)
58 views

Assignment - Week 6 (Generics, Comparable) : 0. Warm-Up

The document describes assignments involving generics, comparable interfaces, and collections in Java. It includes tasks to: 1. Define set operations like union, intersection, and difference that work on any type using generics. 2. Make a Person class comparable based on name and implement additional comparators. 3. Create an Iterable that iterates through squared numbers and a method to check if an array is symmetrical regardless of element type.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Assignment - Week 6 (Generics, Comparable) : 0. Warm-Up

The document describes assignments involving generics, comparable interfaces, and collections in Java. It includes tasks to: 1. Define set operations like union, intersection, and difference that work on any type using generics. 2. Make a Person class comparable based on name and implement additional comparators. 3. Create an Iterable that iterates through squared numbers and a method to check if an array is symmetrical regardless of element type.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Assignment - Week 6 (generics,comparable)

0. Warm-up
a) Set operations:
Define these static methods; each of them receives 2 parameters of type Set<String>
and returns a new set of the same type:
i) union()​ - returns a set with all elements of both sets combined.
ii) intersection()​ - returns a set with only the elements common to both sets.
iii) difference()​ - returns a set with only the elements found in first given set, but
not in 2nd one.
Note: your code should NOT modify in any way the input sets.
Then write some code to test them.
Example:
set1: [aa, bb, cc]
set2: [bb, cc, dd]
union: [aa, bb, cc, dd]
intersection: [bb, cc]
set1-set2: [aa]
set2-set1: [dd]

b) Generic set operations:


Make the previous methods more generic, so they will work on sets of any type of
objects. Test them on sets of Integer, Double, Person, etc...
i) question: how much did you need to change your method’s code? what about
your test code?
ii) question: why is this way (using generics) better than just working with
Set<Object>?

c) Comparing Persons​:
i) Write a class Person with fields: cnp, name, age, height (also having a
constructor with values for all fields, and toString)
ii) Make it sortable by name by default, by implementing Comparable based on
name. Test it by having adding some persons in a sorted type of Set, and
then print them in the default iteration order. Question: do you also need to
override equals & hashCode for this to work?..
iii) Implement a separate comparator which will order persons by cnp
(ascending), and test it. Try to test it by adding same persons to a new sorted
set, but which uses by default this specific comparator to keep the set sorted,
and the just iterate over that set and print them.
iv) Implement another comparator which orders persons first by height
(ascending) then by age (descending). Test it on a list of persons, making
sure it works correctly for all cases (persons of same height..). Try to test it by
adding persons in a List, then using Collections.sort() to sort it (using this
specific comparator), and then print the contents.
1) Question: what happens when you have 2 Persons with same height
and age, but different details in rest - how are they added to set and
ordered?... (and does this depend on overriding equals/hashCode?)

d) Squares Iterable:
Write a class SquaresIterable which implements Iterable<Long> and allows to iterate
over the squared values of all positive numbers, starting from 1. (you’ll probably need
to define also a SquaresIterator class, to return as the result from ​iterator() method​..)
Test it then in a for loop, printing all squares of numbers which are less than a max
limit value (like 100_000).
Questions:
- How do you write the stop condition here?
- Could we end the loop in some other way except using a break? (like making
the iterator itself stop when the limit was reached; but how do you make that
limit configurable from outside the iterator/iterable?)

e) Symmetrical array:
i) Write a static method ‘boolean isSymmetrical(int[] array)’, which receives an
array of int values and returns true if the array is symmetrical - meaning the
order of elements from start to end is the same as from end to start.
ii) Make the method more generic, to be able to work with an array of elements
of any type (instead of just int). Test it on some arrays of String, Double,
Person..
Question: how much of the code did you need to change for this? (anything
besides the method signature? why?)

f) Palindrome​:
Write a method ‘boolean isPalindrome(String)’ which takes a phrase as a String,
eliminates the spaces between words (if any), lowercases it, then returns true if the
resulting string is a palindrome - meaning it has the same value if read backwards or
forwards.

Try to reuse the isSymmetrical() methods from previous exercise!


(hint: you will need to convert your String to an array of letters; but note that
.toCharArray() will not work, as it returns a char[] - an array of primitives, not usable
with your generic isSymetrical method; try instead to call String.split(“”) to get a
String[] array...)

Your palindrome method should respond with true for strings like these:
“aerisirea”, “rotitor”, “​calabalac”, “​Ene purta patru pene”​, “​Ion a luat luni vinul tau la noi”,
“Step on no pets”, ​“​Never odd or even”,​ “​Was it a car or a cat I saw”
(more info: ​https://en.wikipedia.org/wiki/Palindrome​ , ​https://ro.wikipedia.org/wiki/Palindrom​ )
1. Stock Market
Create a class called ​StockMarket​ that can record and query stock updates.

A stock update is defined by these properties:


● Stock code (e.g “AMZN”, “MSFT”)
● Time of the update (use the java.util.Date class)
● Price
Note: to be able to use this in maps and sets, you should probably override equals() and
hashcode(), as well as implement Comparable<StockUpdate>.

The following methods should be supported by the StockMarket class:


● add(StockUpdate update)
● List<StockUpdate> queryUpdates(Date from, Date to)​: get all stock updates
between two dates
● List<StockUpdate> queryUpdates(Date from, Date to, String stockCode)​: get all
stock updates between two dates ​for a stock code
● Double getPrice(Date date, String stockCode)​: gets the price that a stock had at a
given date. Note that there may not be an entry for that exact date, so you need to
search for the last stock update that happened before the specified date.
Hint: the TreeSet class has a “ceiling” method that could be useful here:
https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#floor-E-
● Map<String, Double> getPrices(Date date)​: gets the prices for all stocks at a given
date. The note from previous point applies here as well.

Note: to store the updates, you may use multiple collections if needed. There is no restriction
to only use a single collection here. For example, you may choose to have a collection with
all updates for all codes, as well as one collection for each individual stock.

Create also a test class and add tests to it (of type JUnit) to check that StockMarket class
works as expected.
2. Media Library
Write a class hierarchy for a virtual library that holds books, videos and music.
Define and implement the following entities, fields and methods:

1. MediaEntity (base class for Book, Video and Mp3 classes)


○ type
○ title
○ noOfDownloads

2. Book
○ author
○ publisher
3. Video
○ duration
○ fullHD
4. Mp3
○ singer
○ album

5. Library:
○ List<MediatEntity> top20​ - keeps only the last 20 most accessed media
entities according to noOfDownloads field
○ List<MediatEntity> archive​ - keeps the rest of media entities (outside of top
20)

Hint: use inheritance by having all supported media types inherit a common base class (e.g
MediaEntity).

Offering functionalities for:


● searching by MediaEntity properties
● adding a new MediaEntity
● archiving all the media entities that are not included in the last 20 most accessed
entities
● update for the noOfDownloads field of a MediaEntity

Hint: start with the basic functionality first: first make the library store the complete list of
MediaEntities, then add the “top20” functionality to it.

Testing
Create also a test class and add tests to it (of type JUnit) to check that your main code works
as expected.

An example of test scenario:


- create an instance of the library that contains: 15 books, 5 videos and 7 mp3
- Check that they were added to the relevant list – top20 or archived – according to the
noOfDownloads field of each
- display all the media entities that are of type video
- update noOfDownloads field for one MediaEntity (that is included in the archived list
in order to make it eligible for top20 list)
- display all the top20 most accessed media entities

You might also like