Loading...
Logo
Processing Forum
Greetings all,

I have a HashMap that uses a String as they key, and a composite Object as value. I have been able to convert the keys used in the hashmap into an array of Strings with a two step process:

Copy code
  1. HashMap words;
  2. String[] keyWords;
  3. Object[] temp;
  4. temp = words.keySet().toArray();
  5. keyWords = new String[temp.length];
  6. for(int i=0; i<temp.length; i++) {
  7.       keyWords[i] = temp[i].toString();
  8. }

Is there anyway to do away with the temporary Object[] array and the for-loop to convert the objects to strings?
Thanks!

Replies(9)

Copy code
  1. HashMap<String, Object> words = new HashMap<String, Object>();

  2. String[] keyWords;

  3. words.put("A", new Object());
  4. words.put("B", new Object());
  5. words.put("C", new Object());

  6. keyWords = words.keySet().toArray(new String[0]);
  7. println(keyWords);
Using the Java 1.5 syntax allowed by Processing 1.2+
Ah, ok, I'm still using 1.1, so I'll update now. Thanks! I had no idea you could put a 'new' statement as a parameter to a method. Or I should say, I didn't realize that's what the Javadocs were telling me when I read this:

toArray

public Object[] toArray(Object[] a)
Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method.


Thanks again, I'm learning at lot, really fast!
Yes, I am creating a null sized array because toArray() can create its own array, but will use the type information of its parameter to create the array with the right type...
I finally wrapped up another big project that was monopolizing all my time. Now I have time to get back to this, and I tried this syntax as described by phi.lho in a previous post:

Copy code
  1. String[] keyWds; // Array of key words

  2.   keyWds = words.keySet().toArray(new String[0]);
But when I run it I still get this error message: cannot convert from Object[] to String[]. I am using Processing 1.2.1.
But just futzing around I found that this DID work:

Copy code
  1.   keyWds = (String[]) words.keySet().toArray(new String[0]);

Have you declared the HashMap as I did, with the angle brackets?
No, I thought that was a pseudo-code notation. I had no idea that angle brackets could be used in declarations. I have never come across that in reading up on Processing. Is it a Java convention?. Can you refer me to some documentation on that?
Yes, it is a Java "convention" since v.1.5, introduced relatively recently in Processing. It is called Generics and it is very convenient...
That's very cool! But boy, I really do feel like I'm in the deep end, learning to swim in a hurry.
Thanks!