GeeCON Prague 2014*
The moose likes I/O and Streams and the fly likes Compiler warning when i try to cast my readed input? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Compiler warning when i try to cast my readed input?" Watch "Compiler warning when i try to cast my readed input?" New topic
Author

Compiler warning when i try to cast my readed input?

Hans vogn
Ranch Hand

Joined: Feb 04, 2009
Posts: 46
Hi

I've written a program that can make a couple of quiz questions and save them in an arrayList, and then serialize the arraylist and save it.

Now I'm trying to make a program that can read the saved files and and cast them back to arrayLists. I have now written a method that should read and cast the objects that looks like this:



But when i compile, this shows up:



It accepts to compile and make a class file?

can someone tell me what is wrong here (if anything is wrong)?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

It's not an error but a warning, caused by the case on this line:
Because of type erasure, the JVM can check whether or not the object is an ArrayList, but it can't check the generic type. The ArrayList can contain Strings, Integers, or anything, and the cast will still succeed. It will fail at a later time though, when you try to retrieve elements assuming they are instances of QuizQuestion.

You can get rid of that warning by using the @SuppressWarnings("unchecked") annotation. But again, this may be a source of possible problems at later points if only the first element is an instance of QuizQuestion.


Aside from that, there are some more problems with your code:
1) Don't write "objArray.isEmpty() == false" - write "!objArray.isEmpty()"
2) You are reading two different objects from the ObjectInputStream - one into obj and one into questionList. Are you sure this is what you want?
3) objArray is NOT the object you read from the ObjectInputStream, but a new, empty ArrayList (as created on line 7). As such, the next if-statement will not be executed because its guard is false.

I think you meant the following:
Please from now on follow my advice at the end. If an exception occurs, you will not see it in your code and you will have no idea that something went wrong. It will be nearly impossible to troubleshoot. The least you should do is print it.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Hans vogn
Ranch Hand

Joined: Feb 04, 2009
Posts: 46
Thank you very much

What would happen, if I ran my fisrt code, and the readen object was not an ArrayList<QuizQuestion>?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Compiler warning when i try to cast my readed input?