0

In Javascript we can store values in array like

var arr=[];
arr["name"]="test";
arr["value"]="result";
console.log(arr["name"]);

above mentioned array is storing values like key value pair,my question is this we can achieve in java without using hashmap ? so that we can get value by key in java

4
  • 4
    What's problem with hashmap? It is intended for above purpose only. Commented May 22, 2015 at 18:22
  • "In java we can store values in array like...[code]" no Java will not allow it. Did you perhaps mean JavaScript? "is this we can achieve in java without using hashmap" yes, you can write your own class which probably will behave like Map so in the end it is better to just use one of its implementations like HashMap. Commented May 22, 2015 at 18:25
  • Technically true but probably not the answer you are looking for - use TreeMap Commented May 22, 2015 at 18:27
  • ...and technically the Javascript example you give isn't using an array. It's using a standard Javascript object which in reality is...you guessed it... a hashmap. It uses some tricks so that it can sometimes behave like an array. Commented May 22, 2015 at 18:30

2 Answers 2

2

I mean you could achieve it that way, but it is much less efficient. Searching an array for a specific value will be of O(n) complexity while hashmaps only take O(1) in the best case scenario (with no chaining).

Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible. Arrays are Integer Index based in Java.

HashMap is specifically designed for that purpose.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.