LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 10-10-2005, 09:49 PM   #1
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Rep: Reputation: 60
can you cast arrays? (java)


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?

Last edited by nadroj; 10-10-2005 at 09:53 PM.
 
Old 10-11-2005, 01:36 AM   #2
vladmihaisima
Member
 
Registered: Oct 2002
Location: Delft, Netherlands
Distribution: Gentoo
Posts: 196

Rep: Reputation: 33
It is always helpfull to include all the source and error message (maybe you missed something). Looking over your description everything looks ok (and I saw that on many occasions when people described bugs they desribed perfectly correct things, omiting what was important).

Also you could have changed the title of the thread.
 
Old 10-11-2005, 02:19 AM   #3
spooon
Senior Member
 
Registered: Aug 2005
Posts: 1,755

Rep: Reputation: 51
Try "return (Product[])products.values().toArray(new Product[0]);" because of weird ways in the way that the toArray() methods work.

However, I think that a better way is to just return the Collection "products.values()". Then you can iterate through it like this (Java 1.5):
Code:
public static Collection<Product> getProducts() {
	return products.values();
}
Code:
Collection<Product> products = Product.getProducts();
for (Product prod : products)
	System.out.println(prod);
or this (Java 1.4 and below):
Code:
public static Collection getProducts() {
	return products.values();
}
Code:
Collection products = Product.getProducts();
for (Iterator i = products.iterator(); i.hasNext(); ) {
	Product prod = (Product)i.next();
	System.out.println(prod);
}
 
Old 10-11-2005, 06:16 AM   #4
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Original Poster
Rep: Reputation: 60
alright, thanks guys.

vlad- i did try editing post and changing title, but it only changed it at the top of my thread, not in the forums page where people will see it.

spooon-
that would be odd.. ill try the 'new Product[0]' method first later today after class. also, i thought about just returnint a collection of some sort, Vector for ex., but the method requuires that an 'array..' is returned.
 
Old 10-12-2005, 03:56 PM   #5
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Original Poster
Rep: Reputation: 60
alright.. i guess the method was the first one you suggested, with the '... new Product[0]...'
i asked my teacher about this and thats what he suggested too.
can you not cast arrays, though? or how does this actually solve the problem? (the new Product[0]...)
Thanks though.
 
Old 10-12-2005, 04:39 PM   #6
vladmihaisima
Member
 
Registered: Oct 2002
Location: Delft, Netherlands
Distribution: Gentoo
Posts: 196

Rep: Reputation: 33
(back with a more documented answer)

When you cast between two objects like obj1 = (SomeClass) obj2, obj2 must be of type SomeClass or be a type that inherits SomeClass (otherwise the case would not make any sense).

This is also true for arrays. In the following example the line " v = (String[]) x;" will give an error, because x is Object[] and Object[] does not inherit String[]. On the other hand y contains an object which type is String[] - so no problem at the conversion.

Bottom line is that this behavior is consistent with the strong typing of the language. If you would be allowed to do that cast the runtime could not gurantee that v[0] will not return a bogus result (because you could have added anything in x not just strings)

Code:
class a {
    public static void main(String a[]) {
        Object x[] = new Object[10];
        Object y[] = new String[10];
        String v[];

        v = (String[]) y;
        v = (String[]) x;
    }
}
Now a question. Do you think you would be allowed to do something like "y[1] = new Integer(5);" (for the above example)

Hope this helps
 
Old 10-12-2005, 04:52 PM   #7
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Original Poster
Rep: Reputation: 60
id say no. because you made (demoted?) y to reference an array of Strings, rather than objects. you could, however, store the '..new Integer(x)...' into x, correct?

just before you posted this, coincidently, i was on the java site (http://java.sun.com/j2se/1.4.2/docs/....Object[])) reading about the toArray method in the collection interface, and it kinda made sense of what was said earlier.
Thanks again!

Code:
toArray

public Object[] toArray(Object[] a)

...

    Parameters:
        a - the array into which the elements of this collection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose

...

Last edited by nadroj; 10-12-2005 at 04:56 PM.
 
Old 10-13-2005, 01:34 AM   #8
vladmihaisima
Member
 
Registered: Oct 2002
Location: Delft, Netherlands
Distribution: Gentoo
Posts: 196

Rep: Reputation: 33
Yap, that was my point .
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
type cast alaios Programming 2 07-17-2005 04:58 AM
pointer from integer without a cast bcf2 Programming 7 12-30-2004 02:04 PM
what does a cast in c++ actually do? markhod Programming 2 12-23-2004 09:01 AM
gDesklets weather cast Hammett Linux - Software 1 06-04-2004 05:57 AM
Question on type cast cxel91a Programming 2 12-05-2003 09:13 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:42 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration