LearnFrenzy
Sign in Take a free test

Generics · Exercise 4 of 4

Generics Generics Programs

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Java programs that build reusable, type-safe components with generics. Write each one yourself first, then open the solution – every solution was compiled and run on Java 21, and the output shown is the real output.

Question 1 Medium

Implement a generic LinkedList<E> with add, get, size, contains and Iterable support, and use it with Strings and Integers.

Question page & discussion
Question 2 Easy

Write generic static methods min, max and clamp bounded by Comparable, and use them with Integers, Strings and LocalDates.

Question page & discussion
Question 3 Medium

Write a generic Cache<K, V> that loads missing values through a Function<K, V>, counts loads, and supports invalidate; use it for squares and for user names.

Question page & discussion
Question 4 Hard

Build an EventBus where handlers subscribe with a Class<E> and a Consumer<E>, and publish(Object) delivers each event only to handlers of its exact type; publish some order and payment events.

Question page & discussion
Question 5 Medium

Write a generic binarySearch(List<T>, T key, Comparator<? super T>) that returns the index or −(insertion point) − 1, like the JDK; test it with numbers and with products sorted by price.

Question page & discussion
Question 6 Medium

Write a generic Pair record and static generic methods zip(List<A>, List<B>) → List<Pair<A,B>> and unzipFirst, and use them to combine names with marks and find the topper.

Question page & discussion
Question 7 Medium

Implement a generic fixed-capacity circular queue (ring buffer) with offer, poll, peek and size, using an Object array internally with a safe unchecked cast; test with log messages.

Question page & discussion
Question 8 Hard

Implement a generic binary search tree BST<T extends Comparable<T>> with insert (ignoring duplicates), contains, in-order traversal and height; test with integers and strings.

Question page & discussion
Question 9 Medium

Write a generic Rule<T> record (message + Predicate<? super T>) and a validate(T, List<Rule<T>>) method that returns all failed messages; validate a username String and an age Integer.

Question page & discussion
Question 10 Hard

Because generics cannot use + on T, write a generic Arithmetic<T> strategy interface with implementations for Integer and BigDecimal, and a generic sum and dot-product that work with either.

Question page & discussion
All exercises doneBack to GenericsRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links