Reputation: 153
I have defined the class User:
public class User
{
public String id;
public String passWord;
public User(String id, String passWord)
{
this.id = id;
this.passWord = passWord;
}
}
Then I created a list of Users:
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
users.add(new User("u1", "abc"));
users.add(new User("u2", "aaa"));
users.add(new User("u3", "bba"));
To find the user in the list with a given id and password I did:
Scanner input = new Scanner(System.in);
System.out.print("User: ");
String user = input.next();
System.out.print("Password: ");
String pass = input.next();
int N = -1;
for (int n = 0; n < medicos.size(); n++)
{
if (user.equals(users.get(n).id) && pass.equals(users.get(n).passWord))
{
N = n;
}
}
Is there a simpler way to get the element of the list containing the given id and password, for example like using a method similar to contain?
Upvotes: 0
Views: 43
Reputation: 1583
Use a HashMap
. You can still use an ArrayList
of User
if you want, but you could also add the username and password to a HashMap
with the username as the key and the password as the value. So, for instance, you could do something like this:
Map<String, String> users = new HashMap<>();
users.put("u1", "abc");
users.put("u2", "aaa");
users.put("u3", "bba");
Scanner input = new Scanner(System.in);
System.out.print("User: ");
String user = input.next();
System.out.print("Password: ");
String pass = input.next();
String pword;
if (users.containsKey(user)) {
pword = users.get(user);
}
Now the variable pword
contains the password for the user named "user" (obtained from the Scanner
).
Upvotes: 2