John Smith
John Smith

Reputation: 6207

Java, convert hashMap to array or empty array

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;

Upvotes: 0

Views: 211

Answers (1)

Eran
Eran

Reputation: 394146

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.

Upvotes: 2

Related Questions