java – indexOf()将找不到自定义对象类型
发布时间:2020-05-25 18:15:41 所属栏目:Java 来源:互联网
导读:以下代码没有给我正确的答案. class Point { int x; int y; public Point(int a,int b){ this.x=a;this.y=b; }}class A{ public static void main(String[] args){ ArrayListPoint p=new
|
以下代码没有给我正确的答案. class Point {
int x; int y;
public Point(int a,int b){
this.x=a;this.y=b;
}
}
class A{
public static void main(String[] args){
ArrayList<Point> p=new ArrayList<Point>();
p.add(new Point(3,4));
p.add(new Point(1,2));
System.out.println(p.indexOf(1,2));
}
}
这给出了-1; 一般来说,如果给出了arraylist of point,我们怎样才能找到数组中特定点的索引? 解决方法indexOf需要对象作为输入.如果找不到要传入的对象,则返回-1.您需要将您要查找的arraylist中的位置作为输入传递给indexOf函数.在这种情况下,您还应该为您的类重写hashcode和equals.在您的类Point中覆盖hashcode和equals.然后,一旦创建了此类Point的实例(使用new关键字)并将它们添加到arrayList,就可以使用任何Point对象作为indexOf调用的参数对arrayList使用indexOf调用. 类点 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;
}
}
类测试(你称之为“a”): import java.util.ArrayList;
public class Test {
public static void main(String[] args){
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));
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
