How to get an instance of java.util.Map.Entry?

    3 answers 3

    Map.Entry - interface. You cannot create its object. You can create class objects, but not interfaces. At the same time, no one bothers to define the interface - by creating your own class, and after that, use class objects using the interface.

      You cannot get an instance of the interface. Or do you need this ?:

      Map<Integer, String> map = new HashMap<Integer, String>(); for (Map.Entry<Integer, String> entry : map.entrySet()) { Integer key = entry.getKey(); String value = entry.getValue(); } 
      • one
        In addition, you can add the following: Each element of an associative array, described by the Map interface, has a Map.Entry interface type, which provides three main methods: getKey () returns the key of the element; getValue () - returns the value of the element; setValue (Object value) - changes the value of an element. The entrySet () method defined in the Map interface will allow you to get all the elements of an associative array as a set of objects of type Map.Entry. - Kobayashi_Maru

      the impossible is sometimes possible:

        java.util.Map.Entry < String, String > s = new java.util.Map.Entry < String, String > () { @Override public String getKey () { return null ; } @Override public String getValue () { return null ; } @Override public String setValue ( String value ) { return null ; } }; 

      attention to the question - why do you need it? In this form, the code does not look the best way, in most cases it is better to make your own class which implements this interface.

      • I did that. - Phynn
      • one
        did the right thing. although by and large, this example is not creating an instance of an interface, but creating an instance of a nameless abstract class that inherits the interface you need :) - jmu
      • @jmu Again, no. This is the creation of an object from a new anonymous class (a full-fledged class that does not have its own access interface) with the specified interface. You cannot create objects from abstract classes. - dnalchemist