Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compiler warning when i try to cast my readed input?

 
Hans vogn
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hans vogn
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much

What would happen, if I ran my fisrt code, and the readen object was not an ArrayList<QuizQuestion>?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic