java - 如何在 android 中获取 indexof(object) 请参阅我的示例以了解
问题描述
请阅读此示例以了解我的问题,谢谢。
像这样向arraylist添加一些数据后:
ArrayList<UserInfo> user_info = new ArrayList<>();
user_info.add(new UserInfo(1, "alex", "26"));
user_info.add(new UserInfo(2, "daniel", "23"));
user_info.add(new UserInfo(3, "veka", "19"));
我想获得“veka”的索引,我该怎么做?我知道如何使用 get index of 来处理数组字符串,但我如何使用带有UserInfo的示例来做到这一点
谢谢。
这是UserInfo.class
public class UserInfo {
private int id;
private String UserName;
private String UserAge;
public UserInfo(int id, String userName, String userAge) {
this.id = id;
UserName = userName;
UserAge = userAge;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getUserAge() {
return UserAge;
}
public void setUserAge(String userAge) {
UserAge = userAge;
}
}
解决方案
You should implement the override the equals
method. This will be used by the indexOf
function.
An example is here
public class Point {
int x;
int y;
public Point(int a, int b) {
this.x=a;this.y=b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
ArrayList<Point> p=new ArrayList<Point>();
Point p1 = new Point(3,4);
Point p2 = new Point(1,2);
p.add(new Point(3,4));
p.add(new Point(1,2));
System.out.println(p.indexOf(p1));
With this information you can update your class and then it will work.