我的对象的 ArrayList,indexOf 问题

编程入门 行业动态 更新时间:2024-10-28 20:25:15
本文介绍了我的对象的 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:关键词]

本文发布于:2023-04-16 10:26:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/885065.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   ArrayList   indexOf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!