Home > Enterprise >  Java alternative of javascript dynamically constructed object
Java alternative of javascript dynamically constructed object

Time:09-27

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".

CodePudding user response:

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);
  • Related