I was messing around with Java and hashmaps on a Computer at School.
I was able to instantiate an Entry
of type String, Integer
on the fly. Then add it to an ArrayList
of Entrie
s. I emailed this code to myself for later.
However on my home computer and my laptop, it wont let me. Same exact code says
The method
entry(string,int)
is undefined for typeMap
The code is:
Map.Entry<String, Integer> entry = Map.entry(largest, maxCount);
I think this has something to do with the fact that Map.Entry
is an interface?
As google results seem to say you have to make your own Entry
class to do this? But did that change in newer versions of Java? Why was I able to execute this code just fine earlier?
Lookup the Javadoc of this method. It says:
Since: 9
Which means that this method was added in Java 9.
So your machine at home likely did not have Java 9 or newer.
Run java -version
and javac -version
in your CMD to verify your version. Then install a more recent Java (for example from AdoptOpenJDK ).
In case you are searching for a solution that works without Java 9, you can use something like:
Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<String, Integer>(largest, maxCount);
As explained in more detail here: Java - How to create new Entry (key, value)
You said:
As google results seem to say you have to make your own Entry class to do this?
That is true for versions before Java 6. The mentioned class AbstractMap.SimpleEntry
was added in Java 6 and can be (ab)used for this purpose. Before that, you would have to create your own implementation.
Another option, which might arguably be better, could be to create your own little class to hold that data and then give it a proper name.
For example, instead of having a Map.Entry<String, Integer>
that stores a person by his String name
and int age
, why not create a Person
class directly:
public class Person {
private final String name;
private final int age;
// Constructor and getters, ...
}
Is much more readable, easier to maintain and extend.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.