0

I have a hashmap containing objects created via a constructor. These objects are in the hashmap

I have a function that compares two arrays. The one array has been manually created, but the second array is created via a method. I need only the values from the hashmap.

String[] checkOne= { "1.2:3,4:Brown", "1.1:5,4:Green" };

Map<String,RoundBrick> hashMap = new HashMap<String, RoundBrick>();

public void addBrick(RoundBrick roundBrick){
    hashMap.put(roundBrick.getRef, roundBrick)
}

checkBrick(getBricks(), one){
...
}

public static boolean checkBrick(Brick[] brick, String[] checkOne){
...
}    

Where I am stuck is with this method...

public Brick[] getBricks(){

How do I convert the objects from the hashmap to an array, so I can compare the contents of the two arrays? I can go...

public Brick[] getBricks() {   
Brick[] bricks = {hashmap.value().toArray()};   
return bricks;    
}

But this give error saying cannot convert from Object[] to Brick

  • if I take .toArray() out, I get a "cannot convert from Collection< RoundBrick > to Brick"
  • if I change .toArray() to .toString(), I get a "cannot convert from String to Brick"

If I change the method to the following...

public Brick[] getBricks() {
    String a = Arrays.toString(hashmap.values().toArray());
    return a;
}

The error I get on "a" is "cannot convert from String to Brick[]"

And when adding the line below, it prints out the array.

System.out.print(hashmap.values());

[1.2:3,4:Brown, 1.1:5,4:Green]

can anyone point me into the right direction?

1
  • Why you are doing Arrays.toString(? toArray retruns Object[] array, loop it and cast to Brick and add it to Brick[]\ Commented Jun 29, 2012 at 19:08

1 Answer 1

3
public Brick[] getBricks() {   
    return hashmap.values().toArray(new Brick[0]);   
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I tried so many variations and the answer was so simple!
It would also be just as direct (perhaps save a bit on garbage collection) to implicitly return hashmap.values().toArray(new Brick[0]), but this is good anyway.
I removed the useless variable

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.