0

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

Jeffplays2005
  • 172
  • 15

1 Answers1

1

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);
knittl
  • 246,190
  • 53
  • 318
  • 364
  • well "similar" means `{world=the world, hello={one=1}, list=[1, 2], array=[I@58d25a40}` with maps and lists and better not with arrays. (`{ "world": "the world", "hello": { "one": "1" }, "list": [1, 2], "array": [1, 2] }` as json) – zapl Sep 22 '22 at 12:32