I have developed a parsing program to handle large csv files and
compute sums. The program was
developed and successfully tested using only String objects. I want
replace String objects with
StringBuffer. The file is a record of electricity consumption
collected every fifteen minutes.
The total consumption must be summed.
The file contains duplicate lines and the first spec was to remove
duplicates. This is
accomplished by adding each line as a String object to a HashSet. So
this is where I started in
replacing String with StringBuffer. The problem is that the
computations are wrong when the
StringBuffers replace the Strings in just this one line of code.
Here is the program in pseudo code:
//eliminate duplicate lines
//when lines were added as String objects
//program produced accurate computations
String nextLine = null;
nextLine = getLine();
while(nextLine != null){
hashSet.add(new StringBuffer(nextLine));//change#1
nextLine = getLine();
}
//get the lines
while( //the collection has more elements )
Iterator iterator = hashSet.iterator();
String unitData = null;
unitData = new String ( (StringBuffer)( iterator.next() )
);//change#2
//tokenize the String, extract the consumption and
//add it to a data structure for later output.
//no code changes after this point
}
As a reminder, the program ran perfectly when the change#1 and change#2
were written as follows:
#1 hashSet.add(nextLine);
#2 unitData = iterator.next().toString();
Any help as to why StringBuffer produces bad sums is greatly
appreciated.