本文介绍了我的对象的 ArrayList,indexOf 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我对 Java 的 ArrayList 有问题.我创建了一个对象,它包含两个属性,x 和 y.现在我已经在我的 ArrayList 中加载了一些对象.问题是我不知道如何使用我正在搜索的 x 属性找到某个对象的索引.有没有办法做到这一点?
I have problem with Java's ArrayList. I've created an Object, that contains two attributes, x and y. Now I've loaded some object in my ArrayList. Problem is that I don't know how to find index of some object with x atribute I'm searching. Is there any way to do this?
推荐答案
这是您要找的吗?
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object o) {
return (o instanceof Point && getX() == ((Point) o).getX() && getY() == ((Point) o)
.getY());
}
}
public class TestIndexOf {
public static void main(String[] args){
Point p1 = new Point(10,30);
Point p2 = new Point(20,40);
Point p3 = new Point(50,40);
Point p4 = new Point(60,40);
List<Point> list = new ArrayList<Point>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
System.out.println(list.indexOf(p3));
}
}
如果您只想搜索 x 属性,请更改 equals 方法以仅比较 x 值,例如:
If you just want to search on the x property, change the equals method to compare only the x values like:
@Override
public boolean equals(Object o) {
return (o instanceof Point && getX() == ((Point) o).getX());
}
这篇关于我的对象的 ArrayList,indexOf 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论