by Java Q&a Experts

Answers to problems with memory, the Vector class, and the StringBuffer class (x x, 1999)

news
Jul 5, 19992 mins

The JavaWorld experts answer your most pressing Java questions

A separate problem I have occurs when I want to make a large string by continuously adding small strings. Using the + operator to overload the String class takes too much time. How I can do this in a faster way?

A
To answer your dynamic memory question, when you create an object using new, it is like malloc() in C/C++. That is, it allocates memory when you create the object; it is dynamic.

To solve the Vector class OutOfMemoryError problem, keep a thread checking for the total memory and free memory. Then if you run out of memory, release references to some unwanted objects and call gc. fee with the following code.

Runtime rt = Runtime.getRuntime();
long total = rt.freeMemory();
long free = rt.freeMemory();
if(total-free < 5000000) { file://if it is less than 1MB
   file://release refs to some objects here
   file://the systems that create cache will release
   file://LRU objects here
   rt.gc();
}

To answer your string question, use the StringBuffer class. String is an immutable object, which means you can’t change it. Any change would have to create a new Object. In contrast, StringBuffer is much faster and mutable — you can append to it with out creating a new object. Here’s how you do it:

String initialString = "initial ";
StringBuffer sb = new StringBuffer(initialString);
String newString = "some thing new ";
file://use append as many times as you want
sb.append(newString);
file://and when you want to get String
System.err.println(sb.toString());