You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中ArrayList的indexOf方法使用及相关代码问题咨询

How to use indexOf() with custom objects in Java ArrayList

Hey there! Let's walk through how to get indexOf() working correctly when your ArrayList stores custom objects like your mainclass instance. The key thing to remember here is that indexOf() relies on the equals() method to determine if two objects are the same—and the default equals() (inherited from Object) only checks if two objects are the same reference in memory, not if their contents match.

Step 1: Fix your mainclass by overriding equals() and hashCode()

First, you need to define what makes two mainclass objects "equal" (in your case, probably matching name and sname values). Here's the updated mainclass with proper method overrides:

import java.util.Objects;

class mainclass {
    String name;
    String sname;

    // Override equals to compare object contents instead of references
    @Override
    public boolean equals(Object o) {
        // Shortcut: if it's the same object, return true immediately
        if (this == o) return true;
        // If the other object is null or a different type, return false
        if (o == null || getClass() != o.getClass()) return false;
        // Cast to our class and compare the fields we care about
        mainclass other = (mainclass) o;
        return Objects.equals(name, other.name) && Objects.equals(sname, other.sname);
    }

    // Always override hashCode when you override equals (Java convention)
    @Override
    public int hashCode() {
        return Objects.hash(name, sname);
    }
}

I used Objects.equals() instead of direct name.equals() to avoid NullPointerException if name or sname is null—this is a safer approach for real-world use.

Step 2: Complete your test method to use indexOf()

Now you can create a "search object" with the values you want to look for, and pass it to indexOf() to find its position in the ArrayList. Here's the full updated test() method:

public static void test(){
    ArrayList<mainclass> me = new ArrayList <> ();
    mainclass ob;
    for (int i=0;i<2;i++){
        ob = new mainclass();
        System.out.println("Enter name:");
        ob.name = user_input.nextLine();
        System.out.println("Enter sname:");
        ob.sname = user_input.nextLine();
        me.add(ob);
    }

    // Add this search logic
    System.out.println("\n--- Search for an object ---");
    System.out.println("Enter name to search:");
    String searchName = user_input.nextLine();
    System.out.println("Enter sname to search:");
    String searchSname = user_input.nextLine();

    // Create a dummy object with the search values
    mainclass searchObj = new mainclass();
    searchObj.name = searchName;
    searchObj.sname = searchSname;

    // Use indexOf to find the position
    int foundIndex = me.indexOf(searchObj);
    if (foundIndex != -1) {
        System.out.println("Object found at index: " + foundIndex);
    } else {
        System.out.println("No matching object found in the ArrayList.");
    }
}

Key Notes:

  • indexOf() returns the first occurrence of the matching object in the ArrayList. If no match is found, it returns -1.
  • The hashCode() override is required because Java specifies that if two objects are equal (via equals()), their hash codes must be the same. This is critical if you ever use your mainclass in hash-based collections like HashMap or HashSet.
  • If you only care about one field (e.g., just name) for equality, adjust the equals() and hashCode() methods to only compare that field.

内容的提问来源于stack exchange,提问作者Mister M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:20:58