简体   繁体   中英

Application of 2D ArrayList in Java

I want to create a list of usernames, and then each username would correlate to a password. The purpose is when a username is submitted, I would iterate through the username list to look for a match. If matched, I would then ask for the password of that username. I thought of using a 2D ArrayList of String, but do not think it's possible to ask for a username and then check for the password that way. Would the only possible (and not too advanced) way to do this be to create 2 separate ArrayList? If so, how do I make sure that for each name from username list, there is only one correct password in the password list?

Note: I am just recently introduced to Java.

A map from java.util would do what you're looking for much better, you'd be able to do stuff like this:

Map<String, String> namesToPasswords = new HashMap<>();
namesToPasswords.put("user1", "password");

Then namesToPasswords.get("user1") would return "password" which you can do what you please with.

Not only is this a lot easier to think about than cross-referencing arrays, it's a lot faster too. Iterating over an array of length n to find a match is O(n), while looking up an entry in a HashMap is O(1).

Documentation

If by chance you do want to use a 2D ArrayList then this is one way you can do it:

List<List<String>> users = new ArrayList<>(); 

// Fill the 2D List
users.add(new ArrayList<>()); users.get(0).add("Joe Blow"); users.get(0).add("password1");
users.add(new ArrayList<>()); users.get(1).add("John Doe"); users.get(1).add("password2");
users.add(new ArrayList<>()); users.get(2).add("Freddy Flint"); users.get(2).add("password3");
users.add(new ArrayList<>()); users.get(3).add("Tracey Johnson"); users.get(3).add("password4");
users.add(new ArrayList<>()); users.get(4).add("Mike Tyson"); users.get(4).add("I bit off his ear? :D");

// Provide a name that might be in the list
// User Name is case sensative. 
String suppliedUserName = "Mike Tyson";

// Iterate throught the list of User Names & Passwords...
String successMsg = "Can't Find User Named: " + suppliedUserName;
String password;
for (int i = 0; i < users.size(); i++) {
    if (users.get(i).get(0).equals(suppliedUserName)) {
        password = users.get(i).get(1);
        successMsg = "Hey..." + suppliedUserName + "'s Secret Password is: " + password;
        break; //found it so stop the iteration
    }
}

// Display a Success or Fail message.
System.out.println(successMsg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM