0

I have a LoginID database than can contain 1000's of users. Now to check if a user exist or not what am doing is am storing all the LoginID value of my database into an arraylist than checking if it exists or not using

Code:

while(result.next())
{
  String str = result.getString(1);
  LoginID_arraylist.add(str);
}

if(LoginID_arrayList.contains(loginid)
{
    // if exist --> than another query using loginid
}

Is this a good way to achieve my desired result and what are my alternatives.....will it effect my performance if my size grows further..?? I am using MySql and JDBC.

4 Answers 4

4

Don't use ArrayList for doing contains searching. That has O(n) performance. Instead, use a HashSet, which has O(1) lookup.

However, even better is to not query all the rows in the first place. Just make your query:

SELECT COUNT(*) FROM users WHERE login_id = ?

then seeing if the result is 0 or not.

Sign up to request clarification or add additional context in comments.

2 Comments

if i use ResultSet result = statement.executequery("SELECT COUNT(*) FROM users WHERE login_id = ?") .....than if loginid doesn't exist what will result contain....??
@RanRag: 0 if the ID doesn't exist; 1 or more if it does (1 if the ID column is unique).
1

Try using a HashSet instead of an ArrayList.

A set doesn't allow duplicates and is structured for much faster lookups.

Comments

1

The solution would not scale well with extremely large data sets because you still have Big O(N) time for using contains().

You could just as easily pass the current loginId to the stored procedure instead ... then return an additional data set with the goods needed from your second conditional query.

This would save you a trip to the db and save on iterating N times over the list looking for something you could be finding inside your query instead.

Comments

1

I'd use a regular sql select and check if there are any results.

SELECT LOGIN_ID.ID FROM LOGIN_ID WHERE ID = 'loginid'

This way the database can optimize and cache queries as well as take advantage of any indexing on the columns. Plus you'll only be hitting the id column rather than every column in the loginID table.

4 Comments

what will above statement return if loginid doesn't exist..??
@RanRag It would return no records.
if you used the above sql for your jdbc call and the loginid did not exist, then your while loop would never be called. You can catch this case and handle accordingly.
@Marcelo so how will i check that it is returning no records....can u plz show me the if/else condition to do that....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.