GOXR3PLUS
GOXR3PLUS

Reputation: 7265

Faster way to compare String objects

This is a method i use:

public void addSong(LibrarySong song){

    //Check if doublicates exist
    for(int i=0; i<intoPanel.getComponentCount(); i++){  
        if(song.getName().toLowerCase().equals(intoPanel.getComponent(i).getName().toLowerCase()))
            return;
    }

    intoPanel.add(song);    

}

.... to insert a new Component to a JPanel.I do this by checking if the name already exists.This works well,but when i have to D&D or insert manually 100.000 items then is running slower and slower.

My question is:

Can i use something better to do this process faster?Thanks....

Edit: Following an answer i have changed the code to this:

   String name;
   public void addSong(LibrarySong song){

    //Check if doublicates exist
    name=song.getName().toLowerCase();
    for(int i=0; i<intoPanel.getComponentCount(); i++){  
        if(name.equals(intoPanel.getComponent(i).getName().toLowerCase()))
            return;
    }

    intoPanel.add(song);    

}

Upvotes: 2

Views: 78

Answers (3)

Hoopje
Hoopje

Reputation: 12952

First of all, don't add 100,000 items to your user interface. For the amount of user interface items you can add to the interface without confusing your users (a few hundred max), the performance of your linear search will be more than sufficient.

If you want to store more than a few hundred songs you will have to think about both your data structures and the user interface.

You can gain much more, both with respect to performance and with respect to user-friendliness, by choosing the right data structures and user interface. For data structure you can use for example a HashMap<String,LibrarySong>. Then you can use the following code:

if (!song.containsKey(song.getName().toLowerCase()) {
    map.put(song.getName().toLowerCase(), song);
}

which almost runs in constant time.

For the user interface it probably best just to let the user enter a name, and then search the corresponding song in your data structure.

Have you considered using a database for your data storage?

Upvotes: 1

StanislavL
StanislavL

Reputation: 57421

Move the song.getName().toLowerCase() before the loop to do toLowerCase() once.

UPDATE: Actualy it's not good idea to add 100 000 components. Use e.g JList of JTable to represent the songs with a custom CellRenderer

Upvotes: 5

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

You can write a sorted linked list class to store all your values. Because it is sorted, both insert and search will take O(logN) time, as you can use binary search.

Seems like a lot of work and for practical purposes the HashMap or HashSet are probably better.

Upvotes: 1

Related Questions