Link to home
Start Free TrialLog in
Avatar of yarek
yarekFlag for France

asked on

JAVA unique string username Array or list or ArrayList

I am newbie to JAVA
I need to maintain a list of UNIQUE connected usernames. I guess something like  this snippet:

users = new something; // array ? Lists ? Iterator ?

function check_user_exist(newUserName:String):boolean; {
  if (users.indexOf(newUserName)>0 ) retrun true else return false;
// something like this ? This is DELPHI like !
}
The Goal is to maintain a array (lists ? Objects ? ArrayLists ?) of UNIQUE usernames, and CHECK if the username is already present in this array

userName are Strings and not Objects


Avatar of Mick Barry
Mick Barry
Flag of Australia image

public void add(String name)
{
   if (!list.contains(name))
   {
        list.add(name);
   }
}
Avatar of yarek

ASKER

ok
But how to declare list ?
list=new WHAT ?
Avatar of mnrz
mnrz

if you use a Set you dont need to check if it is availabe because Set automatically wont insert if it has already inserted

users  = new HashSet<String>()

but please note this is only works if you add string if you want to add any other object you should implement two methods "equals()" and "hashCode()" so the Sit structure will work fine
Set users = new HashSet();

>>connected usernames

What do you mean by that?
I think he means the users that authenticated by his system and a session has been created for them
for a simple sample;

public static void addUser(ArrayList list, String user) {              
  if (!list.contains(user))
     list.add(user);
}
public static boolean checkUser(ArrayList list, String user) {
   return (list.contains(user) ? true : false);
}
public static void main(String[] args) {
  ArrayList list = new ArrayList();
  addUser(list, "xxx");
  if (checkUser(list, "xxx"))
    System.out.print("yes");
   else
     System.out.print("no");
}
private List<String> list = new ArrayList<String();

public void add(String name)
{
   if (!list.contains(name))
   {
        list.add(name);
   }
}

ASKER CERTIFIED SOLUTION
Avatar of Venabili
Venabili
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial