Java Assignment- 8
Collection Framework & Generics
Basic Questions
- In simple words, explain what the Java Collection Framework is and why it is useful compared to using only arrays.
- Write two clear differences between arrays and collections with one small example for each difference.
- Name the root interfaces Iterable, Collection, and Map, and write one short line describing the purpose of each.
- Create an ArrayList<String>, add three names, and print all names using a for-each loop.
- Create a LinkedList<Integer>, add numbers at the beginning and at the end, and print the final list.
- Use a Vector<Integer> to store numbers 1 to 5, then print its size and elements.
- Use a Stack<String> to push three items, then pop one item and print the popped item and the remaining stack.
- Create a HashSet<Integer> with duplicate values and print the set to show that duplicates are removed.
- Create a LinkedHashSet<String>, add some words, and print the set to show that insertion order is kept.
- Create a TreeSet<String>, add some words, and print the set to show natural alphabetical sorting.
- Create a HashMap<String, Integer> with three key–value pairs and print the value for one existing key.
- Create a LinkedHashMap<Integer, String>, insert three entries, and print them to show insertion order in iteration.
- Create a TreeMap<String, Integer>, insert three entries, and print firstKey() and lastKey().
- Create a Hashtable<String, String>, put two entries, and get a value by key. Add a comment that Hashtable is synchronized.
- Create a PriorityQueue<Integer>, add some numbers, and print the result of two poll() calls to show smallest-first order.
- Use an ArrayDeque<String> as a stack: push three items, then pop one item and print it.
- Convert an array String[] colors = {“red”,”green”,”blue”} to a List<String> using Arrays.asList() and print the list.
- Iterate over any Collection<String> using an Iterator and a while loop, and print each element.
- In one or two lines, explain the main difference between List, Set, and Map.
- Write a simple generic method static <T> void printItem(T item) that prints any given item, and call it with an Integer and a String.
Intermediate Questions
- Create a generic class Box<T> with set(T value) and T get() methods. Create Box<Integer> and Box<String> objects and print their stored values.
- Write a method int countOccurrences(List<String> list, String target) that returns how many times target appears. Test it with an ArrayList.
- Remove duplicates from a List<Integer> while keeping insertion order by using a LinkedHashSet, then convert back to List<Integer> and print the result.
- Sort a List<String> in natural order using Collections.sort(list) and print the sorted list.
- Create a Student class with name and marks. Make Student implement Comparable<Student> to sort by marks ascending. Create a list and sort it.
- Sort the same list of Student by name using a Comparator<Student> (lambda or anonymous class) and print the result.
- Create a PriorityQueue<Integer> that works as a max-heap using a custom comparator. Add numbers and show the poll() order.
- Insert the same three entries into HashMap, LinkedHashMap, and TreeMap. Iterate and print entries of each map to show their different iteration orders.
- Measure and print the time (in nanoseconds) to add 100,000 integers to an ArrayList and to a LinkedList. Print both times with a short note.
- Create a TreeSet<String> with a comparator that sorts by string length, and by natural order when lengths are equal. Add words and print the set.
- Given a sentence, use a HashMap<String,Integer> to count the frequency of each word (split by whitespace) and print the map.
- Iterate over an ArrayList<Integer>, try to add a new element during the for-each loop, catch ConcurrentModificationException, and print a friendly message.
- Convert the keys of a Map<Integer,String> to a List<Integer> and print the list.
- Create a list using Arrays.asList(1,2,3). Try to add(4) and catch UnsupportedOperationException. Print a short explanation.
- Write double sumNumbers(List<? extends Number> nums) that returns the total as double. Test with List<Integer> and List<Double>.
- Write void addOneToFive(List<? super Integer> list) that adds numbers 1 to 5. Test with List<Number> and List<Object>.
- Write a generic method static <T> T firstOrNull(List<T> list) that returns the first element or null if empty. Test with lists of different types.
- Create a generic class Pair<K,V> with fields, constructor, getters, and toString(). Create a Pair<String,Integer> and print it.
- Use a TreeMap<String,Integer> to store student marks. Print entries in a sub-range from “A” (inclusive) to “M” (exclusive) using subMap.
- Safely remove all even numbers from a List<Integer> by using an explicit Iterator<Integer> and iterator.remove(). Print the final list.
Advanced Questions
- Implement a simple fixed-size LRU cache using LinkedHashMap<K,V> with accessOrder = true and removeEldestEntry. Demonstrate by adding and accessing keys, and show which key gets evicted.
- Create a generic utility class MinMax<T extends Comparable<T>> with methods T min(List<T>) and T max(List<T>). Test with List<Integer> and List<String>.
- Write a method List<T> mergeSorted(List<T> a, List<T> b) where T extends Comparable<T>, which merges two already sorted lists into a new sorted list without calling sort(). Test with integers.
- Build an index of file names by extension using Map<String, List<String>>. Given an array {“a.txt”,”b.java”,”c.txt”,”d.md”}, produce a map like {“txt”:[…],”java”:[…],”md”:[…]} and print the result.
- Create an Employee class with fields dept, salary, name. Sort a list of employees by dept (asc), then by salary (desc), then by name (asc) using Comparator chaining. Print the sorted list.
- Compare HashSet and TreeSet lookup speed: insert 10,000 random integers into each, then time 1,000 random contains() checks on each set. Print both times with a short note.
- Implement GenericStack<T> backed by ArrayList<T> with push(T), T pop(), and T peek(). Test with Integer and String.
- Write a generic copy method static <T> void copy(List<? super T> dest, List<? extends T> src) and demonstrate copying from List<Integer> to List<Number>.
- Create a TreeSet<String> with a case-insensitive comparator. Add “apple”, “Banana”, “APPLE”, and “banana”, then print the set to show that case-insensitive duplicates collapse.
- Compare ArrayList vs LinkedList for three operations: get(index) in the middle, add(index) in the middle, and add at the end. For each operation, run a small timing test and print a brief conclusion.