contains方法的源碼是用equals()比較的,也就是說比較的是地址,所以要在類中重寫equals()方法.看代碼如何實(shí)現(xiàn)的:
User類
package test3;
public class User {
private String name;
private String pswd;
public User(String name, String pswd) {
this.name = name;
this.pswd = pswd;
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
@Override
public String toString() {
return "User [name=" + name + ", pswd=" + pswd + "]";
}
public boolean equals(Object obj) {
if(this==obj)//地址相同
return true;
else if(obj!=null&&obj instanceof User) {
User u=(User)obj;
return this.name.equals(u.name)&&this.pswd.equals(u.pswd);
}
else
return false;
}
}
main中:
package test3;
import java.util.ArrayList;
import java.util.Scanner;
/*3.創(chuàng)建一個(gè)User類樟插,包含name和password兩個(gè)成員變量.
* 向一個(gè)ArrayList對(duì)象添加5個(gè)User對(duì)象庸追,
* 這5個(gè)User對(duì)象的成員變量的值分別為name="1",password="a",
* name="2",password="b",
* name="3",password="c",
* name="4",password="d",
* name="5",password="e"。
* 然后創(chuàng)建一個(gè)User對(duì)象彩匕,這個(gè)User對(duì)象的成員變量為name="3",password="c",
* 然后使用contains方法測(cè)試這個(gè)對(duì)象是否包含在ArrayList對(duì)象中。
*
*/
public class Work2 {
public static void main(String[] args) {
ArrayList<User> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for(int i=0;i<5;i++){
System.out.println("請(qǐng)輸入姓名");
String name = sc.next();
System.out.println("請(qǐng)輸入密碼");
String pswd = sc.next();
User user = new User(name,pswd);
list.add(user);
}
for(int i=0;i<list.size();i++){
User user = list.get(i);
System.out.println(user);
}
User u = new User("5","e");
Boolean f = list.contains(u);
if(f){
System.out.println("包含");
}else{
System.out.println("不包含");
}
}
}