package org.code2care.generics;
public class Example<K,V> {
public void method() {
K k = new K();
V v = new V();
}
}
If you are working inside a Java IDE like IntelliJ, you would see a compliation error in the above code that reads "Type parameter 'K' cannot be instantiated directly". This is because you cannot create an instance of a generic type parameter directly, it has to be a class.
To better understand this, you can refer to the official Java Generics Tutorial: Restrictions on Generics
Fix:
One workaround would be to create an instance of an Object class which is the parent of all classes in Java and cast it to your generic type.
public void method() {
K k = (K) new Object();
V v = (V) new Object();
}
Facing issues? Have Questions? Post them here! I am happy to answer!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- Fix - Microsoft Windows Error Code: 0xA00F4244 NoCamerasAreAttached - Microsoft
- How to Start Jupyter Notebook on Mac - MacOS
- Steps to Install iOS 17 on your iPhone (Available 18th Sept 2023) - iOS
- [Android Studio] Could not automatically detect an ADB binary - Android-Studio
- Eclipse : Workspace was written with an older version of the product and will be updated - Eclipse
- Keyboard shortcut to close tab in Notepad++ - NotepadPlusPlus
- How to Enable Remote Management using Mac Terminal - MacOS
- Error 404 Tomcat homepage http://localhost:8080/ not displayed - Tomcat