如何检查文件数据库中是否已存在电子邮件地址?

时间:2015-01-30 11:14:45

标签: java arrays list

我有一个数组列表,其中的元素是具有以下字段的类的对象:ID, name, surname, email, password, subject and literature(我正在尝试创建一个保存学生帐户的应用程序)。

literature字段本身是一个最多包含3个元素的数组列表。现在我正在检查String输入是否是现有的电子邮件地址,我想访问Array List的电子邮件字段,但我无法弄清楚如何。你能救我吗?

1 个答案:

答案 0 :(得分:1)

您只需迭代您的数组列表并将每封电子邮件与给定的电子邮件进行比较。

看看这个例子:

这是用户对象声明

import java.util.List;
// This is the user object
public class User {

    public String id;
    public String name;
    public String surname;
    public String email;
    public String password;
    public String subject;
    public List<String> literature;

    public User(String id, String name, String surname, String email, String password,
            String subject, List<String> literature) {

        this.id = id;
        this.name = name;
        this.surname = surname;
        this.email = email;
        this.password = password;
        this.subject = subject;
        this.literature = literature;
    }
}


这是我们填写用户并检查用户ArrayList

中是否包含电子邮件的地方
import java.util.ArrayList;
import java.util.List;

public class main {

    private static List<User> users = new ArrayList<User>();

    public static void main(String[] args) {
        // Creates the users
        User user1 = new User("1", "John", "Addams", "john@mail.com", "j123", "Math", new ArrayList<String>());
        User user2 = new User("2", "Mary", "Stall", "mary@mail.com", "m123", "Math", new ArrayList<String>());
        User user3 = new User("3", "Kurt", "Metten", "kurt@mail.com", "k123", "Math", new ArrayList<String>());

        // Adds the users to the array
        users.add(user1);
        users.add(user2);
        users.add(user3);

        System.out.println(isExistingEmail("john@mail.com")); // True
        System.out.println(isExistingEmail("some mail@mail.com")); // False
    }

    private static boolean isExistingEmail(String email) {
        // Iterates all the users
        for (User user: users) {
            // Checks if the user email is equal to the email parameter
            if (user.email.equals(email)) {
                return true;
            }
        }
        return false;
    }
}