← Back to Advanced Java Course | Chapter 1: Generics | Lesson 1 of 4

Java Generics परिचय

Generics आपको ऐसा code लिखने देते हैं जो अलग-अलग types के साथ काम करे जबकि सुरक्षित रहे, जैसे 'सिर्फ apples रखता है' लिखा box। फिर Java आपको गलत तरह की चीज़ डालने से रोकता है।
Syntax
java
// generic type parameter T
class ClassName<T> { }
List<Type> list = new ArrayList<>();

What are Generics?

Generics Java की एक शक्तिशाली feature है जो आपको classes, interfaces, और methods लिखने देती है जहां data type hard-code होने के बजाय parameter के रूप में पास किया जाता है। यह आपको मजबूत, compile-time type safety देता है, आपका code चलने से बहुत पहले type mismatches पकड़ लेता है।

उदाहरण: What are Generics?

java
// Define the class Main
public class Main {
	// Define the class Box
	static class Box<T> {
		private T value;
		Box(T value) { this.value = value; }
		T get() { return value; }
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Box object and store it in box
		Box<String> box = new Box<>("Hello");
		// Print a line to the console
		System.out.println(box.get());
	}
}

Type Safety Benefits

Generics से पहले, आप ArrayList जैसी किसी collection में कोई भी object store कर सकते थे, जिससे अक्सर runtime ClassCastExceptions होते थे जब आप एक type की उम्मीद में item निकालते लेकिन दूसरी type मिलती। Generics इसे हल करता है compiler से इस mismatch को compile-time पर पकड़वाकर, code ship होने से काफी पहले।

उदाहरण: Type Safety Benefits

java
import java.util.ArrayList;
import java.util.List;
public class Main {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("Apple");
		// list.add(42); // would not compile -- caught by the compiler, not at runtime
		String item = list.get(0);
		System.out.println(item);
	}
}

Eliminating Manual Casting

Generics के बिना, किसी collection से elements निकालने के लिए हर access पर explicit, manual type casting चाहिए होती थी, जो verbose और error-prone था। Generics इस overhead को पूरी तरह खत्म कर देते हैं, compiler को पीछे से अपने आप cast डालने और जांचने देते हुए।

उदाहरण: Eliminating Manual Casting

java
import java.util.ArrayList;
import java.util.List;
public class Main {
	public static void main(String[] args) {
		List<String> names = new ArrayList<>();
		names.add("Riya");
		String name = names.get(0); // no manual cast needed, compiler inserts it
		System.out.println(name);
	}
}

Standard Library Generics

Standard Java Collections Framework, जिसमें List, Set, और Map शामिल हैं, अपने पूरे API में Generics का भरपूर उपयोग करता है। यह सुनिश्चित करता है कि आपके application से गुजरने वाला data store होने के क्षण से लेकर वापस पढ़े जाने तक structured और type-safe रहे।

उदाहरण: Standard Library Generics

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new ArrayList object and store it in list
		List<String> list = new ArrayList<>();
		// Create a new HashSet object and store it in set
		Set<Integer> set = new HashSet<>();
		Map<String, Integer> map = new HashMap<>();
		list.add("data");
		set.add(1);
		map.put("key", 100);
		// Print a line to the console
		System.out.println(list.get(0) + " " + set.contains(1) + " " + map.get("key"));
	}
}

Generic Naming Conventions

Convention के अनुसार, type parameters को single uppercase letters से नाम दिया जाता है ताकि वे असली classes के बजाय instantly placeholders के रूप में पहचाने जा सकें। आम naming parameters में T (Type), E (Element), K (Key), और V (Value) शामिल हैं, और इस convention का पालन करने से अनजान generic code पढ़ना कहीं आसान हो जाता है।

उदाहरण: Generic Naming Conventions

java
// Define the class Main
public class Main {
	// Define the class Pair
	static class Pair<K, V> {
		K key; V value;
		Pair(K key, V value) { this.key = key; this.value = value; }
	}
	static <T> void printItem(T item) {
		// Print a line to the console
		System.out.println(item);
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Pair object and store it in p
		Pair<String, Integer> p = new Pair<>("age", 25);
		printItem(p.key + "=" + p.value);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. primitive types को type arguments के रूप में उपयोग करना, जैसे Box<int>, जो compile नहीं होता क्योंकि generics को reference types चाहिए; Box<Integer> का उपयोग करें।
  2. Box b = new Box(5); जैसी raw type का उपयोग करना, जो type safety खो देता है और वापस casting और ClassCastException समस्याएं लाता है जिन्हें रोकने के लिए generics बनाए गए थे।
  3. यह मान लेना कि List<String> को List<Object> में assign किया जा सकता है क्योंकि String एक Object है, जो एक compile error है क्योंकि generics covariant नहीं हैं।
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.