




















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















































1. What are Generics in Java? Explain the need, advantages and basic syntax of Generics with suitable examples. Generics in Java are a feature that enables you to create reusable and type-safe code. They allow you to define classes, interfaces and methods with a type parameter (i.e., a placeholder for a specific type) instead of using a fixed type like Object. Need for Generics To remove type casting - Without generics, we often have to cast objects to the required type, which can lead to ClassCastException at runtime. To achieve type safety - Generics provide compile-time checking, so you catch type errors early. To write reusable code - The same class or method can work with different types without modification. To avoid code duplication - It reduces the need for multiple versions of the same class for different types. Advantages of Generics Type safety - Prevents ClassCastException at compile time. Eliminates the need for explicit type casting. Promotes code reusability and flexibility. Improves code readability and maintainability. Better performance - No runtime type checking is required. Basic Syntax of Generics The most common syntax is to use a type parameter inside angle brackets <>. class ClassName { //use T as a type } T (Type) is a common type parameter name. You can use any name like E, K, V, N, etc. Generics can be used with classes, interfaces and methods. Examples
public void setValue(T value) { this.value value; } public T getValue() { return value; } }
System.out.println(stringBox.getValue()); // Output: Hello // Using Box (Parameterized type) Box intBox = new Box<>(); intBox.setValue(100); System.out.println(intBox.getValue()); // Output: 100 Difference Between Generic Types and Parameterized Types Generic Types Parameterized Types A class, interface or method declared with type parameters (e.g., , ). A specific type created by supplying an actual type (e.g., , ) to a generic type. Abstract/template. Concrete / specific type. At the time of declaration. At the time of creating an object or using the type. class Box { ... } Box box new Box<>(); Defines the structure to work with different types. Specifies the actual type to be used.
3. Explain Generic Classes and Generic Methods in Java with suitable examples. Generic Classes A generic class is a class that is defined with a type parameter (placeholder) at the class level. The type parameter is specified inside angle brackets () after the class name. It allows the class to work with different types, providing type safety and code reusability. The actual type is provided when creating an object of the class. Syntax: class ClassName { //class members } Example: Generic Class class Box { private T value; public void setValue(T value) { this.value = value;
Public T getValue() { Return value; } } Here, T is the type parameter. The class can store any type of value (Integer, String, etc.). Using the Generic Class public class Main { public static void main(String[] args) { Box intBox = new Box <>(); int Box.setValue(10); } System.out.println (intBox.getValue()); // } The type (Integer) is provided when creating the object. Generic Methods A generic method is a method that is defined with a type parameter (placeholder) at the method level. The type parameter is specified before the return type of the method. It can be used in any class (generic or non-generic). It allows the method to work with different types without being tied to a specific type. Syntax: ReturnType methodName (T parameter) { //method body } Example: Generic Method class Utils { // Generic method to find the maximum of two values public static > T findMax (T a, T b) {
Example: public static void printList (List list) { for (Object elem: list) { System.out.println (elem + " "); } } List li = Arrays.asList(1, 2, 3); printList (li);
Stack: LIFO used for stack operations (legacy). HashSet: Uses hash table. No duplicates. Not ordered. LinkedHashSet: Maintains insertion order. TreeSet: Sorted set (uses Red-Black tree). HashMap: Hash table. No order. LinkedHashMap: Maintains insertion order. TreeMap: Sorted map (uses Red-Black tree). Hashtable Synchronized map (legacy). No null keys/values. Example import java.util.*; public class Example { public static void main(String[] args) { List list = new ArrayList<>(); List. add ("Apple"); list. add ("Banana"); list. add ("Cherry"); System.out.println(list); // [Apple, Banana, Cherry] } }
6. Explain the basic operations performed on Collections in Java with suitable examples. Include: Adding elements Removing elements Searching Checking size Checking whether an element exists Accessing elements
Collections provide methods to add elements into the collection. The exact method depends on the type of collection (e.g., add(), addAll()). add() is used to add a single element. addAll() is used to add multiple elements from another collection. Example: List list = new ArrayList<>(); List.add("Apple"); list.add("Banana"); // add single elements List.add("Cherry"); List moreFruits = Arrays.asList("Mango", "Orange"); list.addAll (more Fruits); // add multiple elements
Bulk operations are methods in the Collection interface that perform an operation on all the elements of a collection at once. They are useful for working with multiple elements efficiently and reduce the need for manual iteration.
Returns true if all elements are present, otherwise false. Useful for checking multiple elements at once. Example: List list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); List list2 = new ArrayList<>(Arrays.asList(2, 4)); boolean result = list1.contains All (list2); System.out.println(result);
The List interface is a part of the Java Collection Framework and extends the Collection interface. It represents an ordered collection of elements (allows duplicate elements). Elements are accessed by their index (position). It provides methods to add, remove, replace and access elements by index. Declaration: public interface List extends Collection {} Key Features of List Ordered maintains the order in which elements are added. Allows duplicates same element can be added multiple times. Index-based access elements can be accessed using an index. Supports all optional operations of Collection interface (add, remove, contains, etc.). Operations add (E element) Adds element at end. add (int index, E element) Adds element at specific index. get (int index) Returns element at index. set (int index, E element) Replaces element at index. remove (int index) Removes element at index. remove (Object o) Removes first occurrence. size () Returns number of elements. isEmpty() Checks if list is empty. contains (Object o) Checks if element exists. indexOf (Object o) Returns first index of element. lastIndexOf (Object o) Returns last index of element. Important Implementations
vector.add(20); vector.add(30); System.out.println(vector); } } IV. Stack Extends Vector class. Provides LIFO (Last In First Out) behavior. Used for undo/redo, expression evaluation, etc. Example: import java.util.*; public class StackExample { public static void main(String[] args) { Stack stack = new Stack<>(); Stack.push("First"); Stack.push ("Third"); stack.push("Second"); System.out.println(stack.pop()); System.out.println(stack.peek()); } }
10. Explain the Set interface in Java Collection Framework. Discuss its important implementations and characteristics with examples. Include: HashSet LinkedHashSet TreeSet The Set interface is a part of the Java Collection Framework and extends the Collection interface. It represents a collection that does not allow duplicate elements. It does not maintain any specific order (except for LinkedHashSet and TreeSet). Common methods: add(), remove(), contains(), size(), isEmpty(), clear(), iterator().
public interface Set extends Collection { // no additional methods } Characteristics of Set No Duplicates: each element must be unique. Unordered (by default): HashSet does not maintain order. Allows at most one null: allow a single null value. Supports all Collection operations - add(), remove(), contains(), size(), etc. HashSet Based on Hash Table (uses hashing). No guaranteed order of elements. Allows only one null element. Provides constant time performance for basic operations (add, remove, contains). Example: import java.util.*; public class HashSetExample { public static void main(String[] args) { Set set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Apple"); set.add(null); System.out.println(set); System.out.println(set.size()); } } LinkedHashSet Extends HashSet. Maintains insertion order of elements.