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

4

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.