Java.lang.illegalstateexception: no primary or single unique constructor found for interface java.util.list

java.lang.IllegalStateException: No primary or single unique constructor found for interface java.util.List

This exception is thrown when an attempt is made to create an instance of an interface that doesn’t have a primary or single unique constructor.

In Java, interfaces cannot have constructors as they cannot be instantiated directly. Interfaces define a contract that classes must implement, and it is the responsibility of the classes that implement the interface to provide a constructor.

Let’s consider an example to understand this better. Suppose we have an interface named List in the java.util package. The List interface defines methods for working with a list of elements. It does not have a constructor as it cannot be instantiated directly.

    <?java
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            List<String> myList = new ArrayList<>();
            myList.add("Item 1");
            myList.add("Item 2");
            myList.add("Item 3");
            System.out.println(myList);
        }
    }
    ?>
  

In the above example, we import the List interface from the java.util package and create an instance of ArrayList (which implements the List interface) using its constructor. We then add some items to the list and print it. This is the correct way of creating a list.

If you encounter the java.lang.IllegalStateException: No primary or single unique constructor found for interface java.util.List exception, it means you are trying to create an instance of an interface directly, which is not allowed. Instead, you should create an instance of a class that implements the interface and use that instance to work with the methods defined in the interface. This ensures that the necessary constructors are available in the implementing class.

Related Post

Leave a comment