0

Is there an equivalent function to array_keys in Java?

Either in the form of arrays or array lists.

2
  • I am trying to get all the keys of a certain level from a multidimensional array of N depth. I have a way to do it in PHP and part of it is the array_keys function. Maybe there is a better way to achieve this in Java. I dont know the elements of the array as it is tree being built recursively on the fly. Commented Jan 28, 2011 at 17:13
  • 1
    You're aware that arrays and Lists in Java don't have "keys", right? They have numeric indices starting at 0. Java uses Maps to associate specific types of keys with objects. Even with that explanation, it's really not at all clear to me what you want to do here. Commented Jan 28, 2011 at 17:28

4 Answers 4

1

The Map collection has a keySet() method, and I think that's the closest thing to PHP's associative arrays in Java.

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

Comments

0

Well, in Java I think the only way to have non integer keys is to use the Map class:

http://download.oracle.com/javase/6/docs/api/java/util/Map.html

And as you can see it has a keySet function.

Comments

0

http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#keySet()

This returns you a Java Set of the keys :)

Another way is to iterate the Map and store the keys in Array/ArrayList

Comments

0

Let me see if got this right, i know that php arrays have keys and values, nevertheless in java thins does not work like that arrays and list are index base, this means that your keys are just index in natural order. if you can shared some code to look what do you exactly need that would be perfect, but in the mean time you might use Map

 Map<String,String> hashMap = new HashMap<String,String>();
 hashMap.put("Key1","Value1");
 hashMap.put("Key2","Value2");
 hashMap.put("Key3","Value3");
 hashMap.put("Key4","Value4");

then you can use keySet() method to get the keys.

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.