Skip to content
Advertisement

Java alternative of javascript dynamically constructed object

I’ve been trying to build an object of some sort which allows dynamic key adding/removing, similar to javascript objects.

I’m trying to do something like this in java(code below is javascript):

const object = {};
object["foo"] = "bar";
console.log(object);
// { "foo": "bar" };
delete object["foo"];
console.log(object);
// {};

I’ve tried doing:

String[] arr;
arr["foo"]="bar";

Although that definitely won’t work as “String cannot be converted to int”.

Advertisement

Answer

In Java, the Map interface provides similar functionality. One such implementation is HashMap. Its base class AbstractMap defines #toString in a way very similar to JavaScript:

final Map<String, Object> arr = new HashMap<>();
arr.put("foo", "bar");
System.out.println(arr);
arr.remove("foo");
System.out.println(arr);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement