gpt4 book ai didi

java - 如何找到一个元素?

转载 作者:行者123 更新时间:2023-12-02 06:07:56 25 4
gpt4 key购买 nike

如何检查集合中的元素是否存在?

public class Account
{
public Account(String username, String password, String lastname, String firstname){
this.username = username;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
}

public String getUsername() {
return username;
}

public String getPassword() {
return password;
}

public String getFirstname() {
return firstname;
}

public String getLastname() {
return lastname;
}


private String username;
private String password;
private String firstname;
private String lastname;
public boolean equals(Object obj)
{
boolean result = false;
if (obj != null && obj instanceof Account)
{
Account p = (Account)obj;
if ( getUsername().equals(p.getUsername())
&& getPassword() == p.getPassword() )
{
result = true;
}
}
return result;
}
}

我的 Servlet

Set<Account> acc = new HashSet<Account>();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
acc.add(new Account("test1", "pass123", "Boom", "Bang"));
acc.add(new Account("test2", "pass123", "Beam", "Beng"));
PrintWriter out = response.getWriter();
String username = "";
String password = "";


if(request.getParameter("Username") != null){
username = request.getParameter("Username");
}
if(request.getParameter("Password") != null){
password = request.getParameter("Password");
}

Account act1 = new Account(username, password, "", "","");

/*
Works only on hard code
Account act1 = new Account("test1", "pass123", "", "","");
*/

out.print("<html>");
out.print("<head><link href='layoutit/css/bootstrap.min.css' rel='stylesheet'>"
+ "<link href='layoutit/css/style.css' rel='stylesheet'>");
out.print("<title></title>");
out.print("</head>");
out.print("<body");
for (Account p : acc)
{
if(p.equals(act1){

out.print("<h3>Click <a href='displayuser.html'>here</a> to continue.</h3>");
}
else{
out.print("<h1>Invalid user account entered.Click <a href='index.html'>here</a> to login.</h1>");
}
}
out.print("</body>");
out.print("</hmtl>");
out.close();
}

最佳答案

Set 有一个“包含”方法以及任何扩展/实现 Collection 的类型。您必须小心地为您的帐户类型实现 equals 和 hashcode。您可以在Object type上找到详细信息。文档。

关于java - 如何找到一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com