This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi, I have been reading Java headfirst and currently working on the example in the book. unfortunately the code won't run on a JVM with a higher version 1.4 because the program need generics (based on what I read in the other site.) . I tried to use ArrayList<String> but the add() method does not read a PrintWriter because it's not a string. Can anyone please advice or help me out with the sample? Thanks in advance.
Generics were introduced in Java 1.5, but it stayed fully backwards compatible. So while you should use generics whenever possible, if you've got code like this that doesn't use it it'll still run in more modern versions. So I'd suggest using the most current version you can: at least 1.6, if not 1.7.
If you still have a problem with it then, let us know exactly what the error is and we can probably help you.
Edit: but if you are going to use generics, you need to get the types right. It's no use declaring a List<String> if you're not intending to put Strings in it! You also need to use generics throughout - creating an ArrayList<String> but then assigning it to a variable of type ArrayListdoesn't achieve anything.
Joined: Apr 04, 2012
I have changed the code and it is now working. thank you for the advice and suggestions. thanks alot for the quick response.
Thanks James Boswell for the advice. I removed the <String>and tried it again.
I thought these were error (first time to encounter it ). Thanks Matthew Brown for clearing to me what generics are.
Note: VerySimpleChatServer.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)
Yeah, those are warnings that you get when you mix generic and non-generic code. The point is that generics give you added type-safety, but as soon as you mix it with non-generic code you lose that. So the compiler lets you know.
Really, you should always use them, except in the specific case where you have to interact with existing non-generic code that you can't change and so you have no choice.