StringBuffer and HashSet

I've been using a HashSet to clear a String[] from duplicates. In the name of optimization I decided to use StringBuffer instead. This, however, made the removing of dublicates not possible. My question is obviously why, but also, is there a significant performance increase in using StringBuffer instead of string in the code below?
String[] getID() {
      StringBuffer idNr[]; //was string before...
      idNr = getDirectory(); //returns  a StringBuffer[] with values
      int underScoreStart;
      int underScoreEnd;
      for (int i = 0; i < idNr.length; i++) {
         underScoreStart = idNr.indexOf(dataSeparetor) + 1;
underScoreEnd = idNr[i].lastIndexOf(dataSeparetor);
idNr[i] = new StringBuffer(idNr[i].substring( underScoreStart, underScoreEnd));
java.util.HashSet sortSet = new java.util.HashSet();
for (int i=0; i <idNr.length; i++) {
sortSet.add(idNr[i]);
StringBuffer[] array; // was string before
int arrayIndex = 0;
array = new StringBuffer[sortSet.size()];
Iterator i = sortSet.iterator();
while(i.hasNext()) {
array[arrayIndex++] = (StringBuffer)i.next();
System.out.println(array[arrayIndex-1]);
StringBuffer tmp; //was string before
for(int j = 0; j < array.length; j++){                           
for (int l =0; l < (int)array.length -1; l++) {
if(Integer.valueOf(array[l].toString()).intValue()>Integer.valueOf(array[j].toString()).intValue()) {
tmp = array[l];
array[l] = array[l+1];
array[l+1] = tmp;
String returnString[] = new String[array.length];
for (int l=0; l < returnString.length; l++)
returnString[l] = array[l].toString();
return returnString;

Thanx for you reply. I have gone back to using String
when copying to the hashset and I have also replaced
my own sorting function with Arrays.sort... The code
looks as below now.
Why is there a performance loss when using string
buffer in the places I've indicated?Mainly because in a number of places String objects are created anyway and then you create StringBuffers copying the content of the String. If these StringBuffers are not used for editing their content then they are wasted space (in addition if you then need to use their String representation you've created yet another String object of the same content again). You also create many array objects which are abandoned - you can reduce this somewhat.
Here's what I think is a tidier solution returning a List of String objects rather than an array though the array is still trivial.
List getId() {
  String[] directory = getDirectory();
  Map workingMap = new HashMap();
  // Populate the map with the integer representations and String representations
  for(int count = 0; count < directory.length; count++) {
    int start = directory[count].indexOf(DATA_SEPARATOR) + 1;
    int end = directory[count].lastIndexOf(DATA_SEPARATOR);
    String s = directory[count].substring(start,end);
    Integer i = new Integer(s);
    workingMap.put(i,s);
  // Now we'll sort the keys and extract the values from the Map in order
  List list = new ArrayList(workingMap.keySet());
  Collections.sort(list);
  List results = new ArrayList(list.size());
  for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {
    results.add(workingMap.get(iterator.next()));
  return results;
}Personally I'd simply return a list of Integer objects and convert back to String only if necessary. In which case the code is very simple.
List getId() {
  String[] directory = getDirectory();
  Set workingSet = new HashSet();
  for(int count = 0; count < directory.length; count++) {
    int start = directory[count].indexOf(DATA_SEPARATOR) + 1;
    int end = directory[count].lastIndexOf(DATA_SEPARATOR);
    Integer i = new Integer(directory[count].substring(start,end));
    workingSet.add(i);
  List results = new ArrayList(workingSet);
  Collections.sort(results);
  return results;
}NB: Yes I know SortedMap is available... yet another way to skin a cat.
Hope this helps
PS: Don't forget those Dukes...
Talden

Similar Messages

  • How do you determine StringBuffer and List capacity?

    hi all,
    I'm curious and would like to post this query that how to determine the StringBuffer and List capacity after read some of the Java Platform performance book. Some of this performance books simply tells number of capacity brieftly without telling what and how does the capacity stand for.
    First, the book mentioned StringBuffer(50). Note, my question is that what is this 50 stand for? 50 Characters? or any. Can someone help me to rectify this?
    Second, List. ArrayList(0.75). And what is this 0.75(by default) stand for? A heap space? Then how many of them? How many objects that can be stored for not to "exceed 0.75"?
    Please help. :)
    regards,
    Elvis
    scjp

    I think the capacity is the CURRENT size of a container. But it is not equal to the number of elements that container currently hold. Just like, a house can have 10 people within, but problably only 3 people at some time. Also, the capacity is not equal to the maximum size, because container can grows automatically.
    For example, a container whose capacity is 50, currently has 30 elements in it. If you add 10 elements more. That is only an addition operation. But if you add 30 elements to it. Then the container first enlarge its capacity according to some arithmetic(a enlarging rate), secondly carry out the addition operation.
    Now that the capacity is the size, it should be a number standing for HOW MANY elements.... In the case of StringBuffer, it should be how many chars; in the case of ArrayList, it should be how many Objects. I do not think 0.75 can stand for a capacity. Prabaly, it was used to describe the enlarging rate when containers need to contain more elements than its current capacity. ( From JDK API, you can see the type of capacity is int ).
    For containers and alike, the questions "how many I can hold" and "how many I am holding", "Do I can enlarge"? are helpful for understanding how it works.

  • StringBuffer and memory issue

    I am having trouble. I have a fairly large string buffer that I use instead of a file. The String Buffer can grow to 5-10 MB.
    When it grows, it seems that the memory of the JVM basically doubles each time.
    To grow the string buffer, I append to it each time, and I have tried making its initial size 1-2 mb for testing purposes.
    Is there some way to prevent the jvm from growing it's memory by 2 X each time? It seems wasteful, and when many users are logged in, 10 mb per 10 users gets to be a lot. Please advise??

    A StringBuffer will indeed double the storage it uses every time an overflow occurs. Given that it has no idea how large its contents will ultimately be, doubling its size on overflow is statistically the best possible approach.
    Seems to me, by choosing a StringBuffer instead of a file, you have considered the memory/speed trade-off and chosen higher speed, higher memory instead of lower speed, lower memory. And isn't it true that the issue is mostly that you are using multi-megabytes of memory, rather than that more megabytes of memory are potentially being wasted? If you are only concerned about the extra allocation that StringBuffer makes, you could call its setLength() method to clean up the waste after it reaches its maximum size.

  • StringBuffer and PreparedStatement

    Does anyone know why prepared statements don't update ? fields when you provide the preparedstatement with a query that is a stringbuffer?
    i.e.
    StringBuffer query = new StringBuffer(500);
    query.append("SELECT * from Customer WHERE CustId = ?");
        try{
                          pstmt = conn.prepareStatement(
                               query.toString()
                    pstmt.setInt(1, 2);
                    result = pstmt.executeQuery();

    Why are you doing this?
    StringBuffer query = new StringBuffer(500);I am doing this before i have to dynmically manipulate the query, i have an array which i have to loop around and keep adding to the query till i get to the end. I cannot do this by simply specifiying the query inside the prepared statmenet paramaeter. The question mark parameters have nothing to do with adding to the query, it works fine if i specify the actual fields CustID = 1; instead of CustID = ?;
    SO my actual point was simply:
    I want to following query inside a string buffer where i can specifiy the paramaeters at a later stage using setInt, setString etc.
    SELECT * from Customer WHERE CustId = ?
    System.out.println(query.toString()); gives:
    SELECT * from Customer WHERE CustId = ?Now the string buffer, I'm specifiy the query reference directly to the preparedsttement i.e. this would be the same if i did conn.preparedStatment(SELECT * FROM CUSTOMER WHERE CustID = ?);
    try{
                          pstmt = conn.prepareStatement(
                               query.toString()
                     );After i use pstmt.setInt(1, 2);
    i get:
    SELECT * from Customer WHERE CustId = ?when it should be:
    SELECT * from Customer WHERE CustId = 2

  • Storing data in Array or StringBuffer and then comparing it to a string

    I want to store some data in a list or an Array (but apparently an Array only holds 10 items?) and then I want to be able to check if myString is equal to any of the posts in the array/list.
    Or if I use a StringBuffer I want to check to see if myString is part of the StringBuffer?
    How do I do this?
    / Elin

    I want to store some data in a list or an Array (but
    apparently an Array only holds 10 items?)Uh, no. Arrays can (theoretically) contain Integer.MAX_VALUE elements.
    and then I want to be able to check if myString is equal to any
    of the posts in the array/list.Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
    Example:String s1 = "foo";
    String s2 = new String("foo");
    System.out.println("s1 == s2: " + (s1 == s2)); // false
    System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==
    Or if I use a StringBuffer I want to check to see if
    myString is part of the StringBuffer?See above discussion on .equals().
    How do I do this?
    Here are some other resources to help you get started with Java.
    The Java&#153; Tutorial - A practical guide for programmers
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • Parse lines out of a StringBuffer and/or InputStream

    I am loading and parsing a ~40MB text file. I am retrieving this file using the JCraft JSch SFTP library. This has given me no problems so far.
    Since I need to process this file line by line, my first approach was to read a character at a time off the InputStream provided by the SFTP library, collect characters until a new line was reached, then parse the line. This proved to be extremely slow. Now I'm pulling 1024 characters at a time into a byte[] from the stream and pushing that array into a StringBuffer until the end of the stream has been reached. It has sped up considerably, but now I don't know what the best way would be to process the buffer.
    What would be the best way to split off and process every line of this file? It seems redundant to pull the whole thing into a string buffer then parse it again by using charAt() and substring() to find and chop off lines. Reading character by character from the stream works in theory but is much too slow. Trying to parse the byte[] with fragments of lines is impractical and error prone.
    Memory is not an issue since it is running on a dedicated batch server, but speed is important.
    Thank you.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    public class ReadLines {
        public static void readLinesFromInputStream(InputStream is)
             throws IOException {
         BufferedReader reader = new BufferedReader(new InputStreamReader(is),
              1024 * 1024);
         String line;
         while ((line = reader.readLine()) != null) {
             System.out.println(line);
    }Piet

  • StringBuffer and .equals()

    this is my test codes:
    public class Testing
         public static void main(String arg[])
              StringBuffer sb1 = new StringBuffer("test");
              StringBuffer sb2 = new StringBuffer("test");
              if (sb1.equals(sb2))
                   System.out.println("1");
                    System.out.println("End");
    }At runtime, the program only prints out End, without the number 1.
    My question is shouldn't the if-statement is equal to true?
    Doesnt .equals() method compare the content of one object to another object?
    thanks for any explanation
    daffy

    String is deliberately immutable (a value object). This means you can pass it around and share it as a data member in many classes without the danger that one class might change its value and therefore surprise all the other classes sharing it. IOW, you can treat it much like a basic type. StringBuffer is class for the efficient manipulation of String contents. It is mutable, and not really intended to be 'passed around' (i.e. made part of a interface, declared as an argument or return type in a non-private method) or shared by classes. In general, a String is passed to a method, manipulated via StringBuffer, then returned as a new String.

  • StringBuffer and CharBuffer

    Hello,
    I just stumled across some weird behaviour. It seems to be impossible to directly create a StringBuffer from a CharBuffer.
    Consider the following code:
    FileReader reader = new FileReader(fileName);
    CharBuffer chars = CharBuffer.allocate((int) fileSize);
    // read complete file
    while(reader.read(chars) != 0);
    reader.close();
    StringBuffer sb = new StringBuffer(chars);This will result in an empty StringBuffer. The reason for this is that StringBuffer uses CharSequence.length() to determine the length of the CharBuffer. However, CharBuffer implements the length method so that it returns the number of remaining bytes, not the bytes already written to the buffer!!! In the example above, the remaining bytes are 0. A work around for this problem is to call
    chars.position(0);before creating the StringBuffer. While this is would work in this case, it might not always be a solution.
    Is this a broken behaviour on behalf of CharBuffer? I mean it implements the CharSequence interface and thus should also behave like a CharSequence. IMHO, the CharBuffer implementation of the length method plainly contradicts the defintion of CharSequence.length().
    Any comments?
    Thank you very much
    draoi

    FileReader reader = new FileReader(fileName);
    CharBuffer chars = CharBuffer.allocate((int)
    fileSize);
    // read complete file
    while(reader.read(chars) != 0);
    reader.close();
    StringBuffer sb = new StringBuffer(chars);This will result in an empty StringBuffer. The reasonHow about using chars.flip() just before creating the StringBuffer. Seems to work for me (but used put instead of read).
    Harald.
    BioMed Information Extraction: http://www.ebi.ac.uk/Rebholz-srv/whatizit

  • StringBuffer and ObjectOutputStream

    I have a question concerning writting a StringBuffer object to a file using ObjectOutputStream (The code snippet is below..). I am merging 2 files together(relatively small files 300 lines). I am storing the merge portion of the 2 files in a StringBuffer. After the merge is done I write this StringBuffer to a file. See code below...
    private void writeToFile()
    try
    ObjectOutputStream outFile = new ObjectOutputStream(new FileOutputStream("Merged.csv"));
    outFile.writeObject(outBuffer.toString()); //outBuffer is a class member
    outFile.flush();
    catch(Exception e)
    e.printStackTrace();
    }//catch
    }//writeToFile
    PROBLEM:
    A snippet of the orginal file that I am reading in:
    Name,GUID,Initial Date,Initial Time,Initial Audit,Last....
    The same line of the merged file that I am writting out:
    ��2openboxs|6openboxes| 'Name,GUID,Initial Date,Initial Time,Initial...
    It is writing out what appears to be junk at the beginning of the file. I did not do any merge at this point. When I print this first line out to the console the junk does not show up?
    If anybody has run in this problem or know what is causing this, then your input would be greatly appreciated.
    Thanks.

    ObjectOuputStream writes a serialized Object to a file. The 'junk' you are seeing is information about the type of object and other things necessary to deserialize the object. You should try reading the API documentation for a class before you start using it. Use the right tool for the job.

  • StringBuffer and letter color

    hi I use
    StringBuffer Wsb = new StringBuffer();
    if (Type1.contains("on"))
    Wsb.append("C1");
    if (Type2.contains("on")){
    if(Wsb.capacity()!=0)
    Wsb.append(",C2");
    else
    Wsb.append("C2");
    } how can I set the color of letter C1, C2 to red, when I use Wsb.append(" <font color="red"> "); I get error

    HJava wrote:
    how can I set the color of letter C1, C2 to red, when I use Wsb.append(" <font color="red"> "); I get errorNot quite sure what you're trying to do.
    If you append as you said, what the compiler sees is two strings with 'red' between them.
    You need to escape the inner quotes in order that they don't terminate the string, viz:
    Wsb.append(" <font color=\"red\"> ");However, even when you get it to work, Wsb will contain
    C1, C2 <font color="red">
    and, even assuming that your spitting it out to some HTML-aware component, that still won't make C1 and C2 come out red.
    Winston

  • HashSet.contains and HashSet.remove specifications

    In the API for java.util.HashSet (this is probably also true for some other parts of the Collections framework), the contains method specification reads "returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))." However, this isn't what I'm experiencing -- it looks like contains returns true iff the set contains an element e such that (o==null ? e==null : o.hashCode()==e.hashCode()). What am I doing wrong here? I have a simplified version of my code below... Thanks.
    public class MyInt {
      int number;
      public MyInt(int number) { this.number = number; }
      public boolean equals(Object other) { return other instanceof MyInt ? this.number == (MyInt)other.number ? false; }
    /* later in the code */
    HashSet<MyInt> set = new HashSet<MyInt>();
    set.add(new MyInt(17));
    set.contains(new MyInt(17));                      // returns false, should return true, right?
    set.size();                                                 // returns 1
    /* modifying MyInt class... */
    public class MyInt {
      public int hashCode() { return this.number; }
    /* then... */
    HashSet<MyInt> set = new HashSet<MyInt>();
    set.add(new MyInt(17));
    set.contains(new MyInt(17));                      // returns true
    set.size();                                                 // returns 0

    kempshall wrote:
    Fair enough, but in case whoever writes the API documentation reads this, I think the wording still needs to be changed: contains does not return true iff there exists at least one element e in the collection such that o == null ? e == null : o.equals(e). Same for remove. Thanks.The API is correct. The fault lies with you not honoring the hashCode() method.
    if o.hashCode() = e.hashCode() then o dose not necessarily equal e.
    if o.hashCode() != e.hashCode() then o necessarily must not equal e
    Hence the exact language would be something like
    o == null? e == null : o.hashCode() == e.hashCode() ? moreThanOneObjectWithSameHashCode? o.equals(e) : true:false;Obviously this is a little more wordy, and strickly speaking it's just implementation detail. Just like the API says, HashSet is a set. And mathematically, the set will contain object o if there is at least one element e such that o.equals(e). You need only to honor the equals() method which states in its documentation.
    it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codesBasically the API is allowed to assume you've correctly overriden both.

  • StringBuffer and JLabel?

    Is it possible to pass a StringBuffer to a JLabel? If so, how is it done?
    I'm trying to create a calculator - so pressing the a number button will append to a stringbuffer. That stringbuffer will then be part of the JLabel.
    Currently, I have:
    <snip>
              //zero listener
              zero.addActionListener(this);
              zero.addActionListener(
              new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   readoutlabel.setText("not sure"); // this is where the string has to be implemented
                   });</snip>
    I tried putting in a stringbuffer but it didn't seem to work.
    advTHANKSance

    You don't have to memorize the documentation. It does help if you look in it to find information you need. In your case you needed a method that makes a StringBuffer into a String. So, if you look in the documentation you'll find there are three such methods. Two of them are different forms of substring() and the third is toString(). A quick look at their descriptions tells you which one you want.
    By all means ask questions here, but (as you will have noticed) people don't always like being used as a resource for looking things up for you.
    You're new to Java, so quite likely it hadn't occurred to you that you needed a String. So put on your thick skin. A look in the JLabel documentation would have told you that... but we already went there.

  • Set and HashSet

    Below is the snippet copied from collection framework tutorial
    import java.util.*;
    public class SetExample {
    public static void main(String args[]) {
    Set set = new HashSet();
    set.add("Bernadine");
    set.add("Elizabeth");
    set.add("Gene");
    set.add("Elizabeth");
    set.add("Clara");
    System.out.println(set);
    Set sortedSet = new TreeSet(set);
    System.out.println(sortedSet);
    My question is Why people like to use "Set set = new HashSet();" rather that "HashSet set = new HashSet();" Both work well
    Is there a difference between them?
    Or just the coding convention nothing else
    I believe Set set = new HashSet() woule be better cause it comes from SUN official tutorial
    thanks

    Set set = new HashSet();Allows for an easy change to work with another kind of Set later on.
    Since the set-variable is set to be a Set, only the actual methods which are
    available in Set will be used by the programmer and thus the type of
    set can still be changed later on by changing the construction of the set and
    not changing anything else in the code.
    Set set = new SortedSet();This rule applies to all possible objects which have a relation to an interface.
    The actual rule says: use the most generic interface available and possible.
    So whenever you would be relying on specific features of for instance the hashSet,
    you shouldn't use this form, but use
    HashSet set = new HashSet();This is only an example, since I honestly have no idea why anyone would ever use specific
    features of a HashSet (and if such features even exist).
    But this example can be valid in other situations.
    kind regards,

  • TreeSet and HashSet

    Hello
    There is a very useful functionality, that I think should be implemented in
    TreeSet nad HashSet
    that is the method: Object get(Object o).
    The method should return the same object from colletion as the parameter object.
    In TreeSet complexity would be log(n), in HashSet would be constant.
    With lack of this functionality one must implement collections on maps, so the unnecessary and more complex type will be used.
    What do you think about this?
    Regards
    Marcin

    This is a strange question :)
    I assume, the OP does not want the object to be returned, but the one from the Set, which is equals to the given object, or null. This might be useful, if operating in a template scenario like JINI, where the given object defines a template (or pattern) that suffices the equals method but does not have further data contained by the object in the Set (which actually should be solved by using a Map). Or if you want to match and return the equal object to have the exact instance. E.g. for a simple Set:public Object get(Object o) {
      for (Object object : objects) {
        if (object.equals(o)) {
          return object;
    }which might be optimized for HashSet (quicker due to buckets) and TreeSet (quicker due to tree structure).
    �dit: Ok, my first scenario was the one. I'd suggest using a Map instead, which is much cleaner wrt. equals/hashcode implementation and contract.
    Message was edited by: stefan.schulz

  • What is the difference between StringBuffer and StringBuilder objects

    hi ,
    Please tell me what is the difference between stringBuilder and stringBuffer classes ..why stringbuffer classes is used more with multiple threads but not stringBuilder which is faster than stringBuffer objects
    Thanks in advance

    Odd. You answer your own question by paraphrasing the first paragraph of
    StringBuilder's javadoc:
    This class provides an API compatible with StringBuffer, but with no guarantee
    of synchronization. This class is designed for use as a drop-in replacement for
    StringBuffer in places where the string buffer was being used by a single thread
    (as is generally the case). Where possible, it is recommended that this class
    be used in preference to StringBuffer as it will be faster under most
    implementations.
    Do you really have a question?

Maybe you are looking for

  • Printing PDDoc with AFExecuteThisScript() doesn't work after an upgrade from SDK 5 to SDK8

    Hello, I have made an upgrade of my plug-in which was developed with the Acrobat 5 SDK. I upgrade it to Acrobat 8 SDK and my print function doesn't work anymore. Actually I print my document using a javascript trusted function instead the function pr

  • Thunderbird not responding, and I need to know how to find out what version of Thunderbird I have?

    I am running Windows 7 Home Premium, use Firefox, but not sure how to tell what version. I have Zone Alarm anti-virus / firewall, iolo System Mechanic, and run them both regularly. I also have a g-mail account, a folder labeled "Gmail" in Thunderbird

  • Question on JRE 1.4.2_06 version

    To all, I'm using WinXP SP1 and just removed the Microsoft JVM, then I've upgraded the jdk to 1.4.2_06 version (with the JRE), somehow I found that the JRE has no server JVM provided, but the JRE folder under the JDK_HOME has it ?! (strange to me) So

  • Cannot save Purchase order when there is Warning Message

    Hi, I have this problem where system do not allow to Save the Purchase order (ME21N) when there is a warning message, for example "W:  Can the delivery date be met?".  By right I can just click enter and save the PO but now the system do not allow to

  • IMac partition screwy

    Hi all, I have a 2010 iMac, I recently discovered a friend was using it and forcing it off with the power button, not shutting it down. Unsurprisingly something went wrong and now on boot it just shows a folder with a question mark. Recovery mode wor