EDIT: SORRY, THIS IS JAVA NOT C++! (lol, i got my work confused)
ill try and be brief.. i have a class named Products, which stores a list of products into a HashMap.
I have the following function in it:
Code:
public static Product[] getProducts() {
return (Product[]) products.values().toArray();
}
it returns (or is supposed to
) an array of Products, which are stored in the HashMap.
- 'products' is the HashMap of 'Product' objects. the .values returns a collection of the elements. the .toArray() is called on the collection object which was returned by .values(), and it returns (obviously) an array.. of _objects_.
In an executable class, i test it with the following (eventually):
Code:
Product[] products = (Product[]) Product.getProducts();
for (int i = 0; i < products.length; i++)
System.out.println(products[i]);
System.out.println();
but i get a classCastException.
However, when i change the code from my Products class to return an array of objects (without the casting obviously)
Code:
public static Object[] getProducts() {
return products.values().toArray();
and change the tester code to:
Code:
Object[] products = Product.getProducts();
for (int i = 0; i < products.length; i++)
System.out.println(products[i]);
System.out.println();
it does work.
any clues?