0

Im a bit beginner. Funny or not, I dont know how to create an empty typed array. My class:

class Depot
{
}

storing them:

private final HashMap<Integer, Depot> depots;
depots = new HashMap<>();

and I want to return them:

public Depot[] getDepots()
{
    if (depots.values().isEmpty())
    {
        return (Depot[]) new Object[0]; ***
    }
    else
    {
        return depots.values().toArray(new Depot[depots.values().size()-1]);
    }
}

as an array. Now when there is no depots, them comes the tricky part. First of all, this line depots.values().size()-1 fails. The return (Depot[]) new Object[0]; seems to be OK, but still triggers an exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Depot;

1
  • 2
    why not just new Depot[0]? Commented Sep 26, 2016 at 13:42

1 Answer 1

2

There's no need to cast. Just create a Depot[] in the first place :

public Depot[] getDepots()
{
    if (depots.isEmpty())
    {
        return new Depot[0];
    }
    else
    {
        return depots.values().toArray(new Depot[depots.size()]);
    }
}

Also note that the length of the array in the else clause should be depots.values().size() (or depots.size()), not depots.values().size() - 1. If you pass a too small array to toArray(), that array will not be used by that method, and a new array will be created.

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

2 Comments

Why not depots.values().size(), if OP prefers so? Once you drop minus one, do you even need a conditional?
@dasblinkenlight It would be pointless to pass a too small array to that method, since it will cause toArray() to ignore the passed array and create a large enough array. Therefore I assumed it wasn't intentional. And while it's true that depots.values().toArray(new Depot[depots.size()]); would also work for the empty case, perhaps it would be a little more efficient not to call values() and toArray() when the Map is empty (though it probably won't make a noticeable difference).

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.