General Java Questions - IV

General Java Questions - IV

Q: I need to programmatically replace an entry in a zip file.I could not quite get it using the ZipOutputStream because it simply creates a new file and writeonly that entry for me. The rest of the original entries are gone.Does anyone have a solution for this?Answer:1) Read the file (myfile.properties) out of the original Zip Archive (original.zip)2) Make your changes, write the file to the file system3) Create a New Archive (originalNew.zip)4) Write your edited file (myfile.properties) to originalNew.zip5) loop through all the entries in the original Zip archive (original.zip), adding them to the newarchive (originalNew.zip) EXCEPT for the file you are replacing (myfile.properties)6) When you're done, erase the original and rename your new one to original.zip.I believe that this may be the only way to do this, since there doesn't seem to be any randomaccess in the ZIP file.--Kevin T. SmithQ: What is better to use: array or vector?Just wondering as I am using Vectors to store large amounts of objects from 50 to 4000 andfile:///C|/330_new/330_new/general_java-IV.htm (1 of 6) [2003-07-22 22:07:55]General Java Questions IVeach one has to be "looked at" every time paint is called...Just wondering if it would be better to use an array, list etc?Answer 1: Since the Vector method uses an array for storage but has extra steps involved ingetting an element, use an array for fastest access.--WBB Java Cert mock exams http://www.lanw.com/java/javacert/Answer 2: arrays are faster, vectors are more dynamic.This should be evident just looking at the amount of code you need to traverse one versus theother. It might also be beneficial to write a linkedlist class and use that. That way you have adynamic container which has potential to be faster than a vector (though still not as fast as anarray). The problem with arrays is that if you need more space than the current size, you haveto hardcode their copying into a bigger array.Conversely, if you never (or rarely) use the entire array, its a waste of space and memory.The following are benchmark test results of vector vs. array (ran on a 200-Mhz Pentium w/ 96Mbytes of memory and Windows95 ):Allocating vector elements: 17910 millisecondsAllocating array elements: 4220 millisecondsAccessing Vector elements: 18130 millisecondsAccessing array elements: 10110 millisecondsOne other reason for vectors being slower that I did not mention above is that vector methodsare synchronized, which creates a performance bottleneck.Hope this helps--MSWQ: Would anyone know the performance issues regarding Vector's?I am actually talking about resource pooling. I have objects that wait in a queue. It is a vectorthat keeps growing, as the queue gets bigger.Do Vectors have much performance hit? Is there a better way to implement vectors to get thebest out of them? Or am I better of creating a fixed size array?Answer 1:If you just want a LIFO or LILO queue, you may be better off withLinkedList than with Vector, as then you'll never have to wait for the contents to be copied.Vectors perform pretty well, but if you know (even roughly) how big you're going to need it tobe, specifying that in the constructor call can help.How sure are you that this will be a performance bottleneck? Premature optimisation is the rootfile:///C|/330_new/330_new/general_java-IV.htm (2 of 6) [2003-07-22 22:07:55]General Java Questions IVof all evil...The Vector class is thread-safe. By that I mean that there is no way to corrupt the internalrepresentation of the data by accessing the vector from more than one thread. However, it isstill possible, very easy in fact, to use a vector in a way that is not thread safe.Consider this code:for (int i = 0; i < vector.size(); i++) {System.out.println(vector.elementAt(i));}It looks safe, but there's a subtle flaw...Q: More about Robot! I met with a problem in using class Robot.mousePress...The compiling process is successful. But when I run it, I receive "IllegalArgumentException:Invalid combination of button flags". I don't quit understand this information. Part of my code isas following:Robot rMouse=new Robot();int button=1;rMouse.mousePress(button);rMouse.mouseRelease(button);I am really confused. Will you please give me some advice? Thank you in advance!Answer: You are not using a valid value for the argument to the mousePress() andmouseRelease() methods. If you check the API documentation, you'll find the valid values are acombination of one or more of the following constants:InputEvent.BUTTON1_MASKInputEvent.BUTTON2_MASKInputEvent.BUTTON3_MASKplus others which represent the Ctrl, Alt, and Shift keys. To press the leftmouse button, you want to use:rMouse.mousePress(InputEvent.BUTTON1_MASK);--Lee WeinerQ: In what situation an exception has to be caught otherwise the compiler will complain?e.g. IOException does NOT have to be explicitly caught, however, SQLException has to becaught otherwise VisalAge will not compile the program.Answer: The only unchecked exceptions in Java are RuntimeException and its subclasses.file:///C|/330_new/330_new/general_java-IV.htm (3 of 6) [2003-07-22 22:07:55]General Java Questions IVThis includes such familiar classes as NullPointerException, ClassCastException, andIndexOutOfBoundsException.IOException is not one of these, and *does* have to be explicitly caught or thrown--jeff_robertsonQ: I wrote a program that use a few RS232 ports. The operators are unskilled and oftenstart multiple instances of the program. Will someone please be so kind and tell me how I canprevent them doing it?Answer 1: The first instance might write a file. Subsequent instances could check for theexistence of that file, or else check it's contents.Another method could involve creating a server socket on a specific port. Subsequent efforts tocreate a socket on that same port would throw an exception.Answer 2: Actually a better way is to (on launch):1) Check if the file exists. If not, create it, open it and run. Leave it open until you quit, uponwhich time you close it.2) If the file _does_ exist, try to delete it. If the delete fails, then someone else has it open,which means another copy of your app is running. Inform the user and quit.3) If you succeeded in deleting it, then you are the first. Now create, open and run.Doing the above prevents the problem of having the semaphore file left around when thesystem crashes. I implemented it recently in one of our apps, and it works like a charm.--Burt JohnsonMindStorm Productions, Inc.http://www.mindstorm-inc.comQ: Can you call a class static abstract method from an abstract class or does it need to beextended and then called from its concrete class?I've been told that abstract classes do not actually have any code in them cause they are like aplaceholder, so I guess you wouldn't bother calling a static method in an abstract class cause itwouldn't have any code to begin with....?Answer: You have been told wrong. Abstract classes can and do have code in them.See, for example, java.awt.Component, an abstract class with a lot of code and no abstractmethods at all. If a class has any abstract method member, directly declared or inherited, it isrequired to be declared abstract. If not, it is the programmer's decision and should be based onwhether it would make sense to have an instance of that class.Perhaps whoever told you was confusing abstract classes with interfaces, which don't containfile:///C|/330_new/330_new/general_java-IV.htm (4 of 6) [2003-07-22 22:07:55]General Java Questions IVimplementation, only abstract method and constant declarations.You cannot declare a method to be both static and abstract. Abstract requires the method to beoverridden before you can have a concrete class, static prevents overriding. You can have astatic method in an abstract class - such a method could be called without creating an instanceof the class, the only thing that is prohibited for abstract classes.And when a subclass of an abstract method has been instantiated, all the methods from theoriginal class will keep the same code in the instance. Most of the time an abstract class willhave abstract methods.However, there are several examples of abstract classes that don't have any abstract methodsat all. Some examples are Component and FontMetrics from the AWT. It doesn't make senseto have just a Component that's not a specific type of component. It doesn't make sense tohave a FontMetrics that doesn't measure any specific kind of Font.Also being abstract never prevents overriding, it just requires overriding in order to derive a nonabstractsubclass. And if a class is a subclass of an abstract class, it only MUST override thosemethods declared abstract. The other methods do not require overriding.Q: I write java about 2 years, but I still confuse one thing that is why should we useinterface???If I need to implement an interface and just use its every methods name.Why shouldn't just write every methods statments in a class, not in interface??I only can think about that if I extend a class, than can implement another or the othersinterface.As you can saw, I really confuse about this. And I do see many books for the reasons , but Ican't get the answer, please tell me !Answer: "Interface" is the Java way to do multiple inheritance, or a better way to think of it is asa way to design plug-ins.For example, let's say we have an application that monitors a network of computers. Ourmonitors might check for web pages, or they may check for other ports, or they may havehooks for hardware checks.The interface to our main control panel is always the same: We need some means to poll themonitor object for an answer. This is the "NetworkMonitor" interface and all network monitorswill share this interface, but they may have a class heirarchy that is very different, for example,port-monitors may all fork a thread that periodically checks whereas our control panel interfacejust asks for the most recent answer; hardware monitors may ask for their data in real-time orover RPC and thus have no need of inheriting from Thread.Because they share the same Interface definition, the control panel application does not needto know if they are polling monitors or real-time monitors because, from the control panel'spoint of view, it does not matter