Results 1 to 2 of 2
  1. #1
    jumpman8947 is offline Member
    Join Date
    Feb 2013
    Rep Power

    Default ArrayList indexOf

    Hi i'm just studying over ArrayLists and i have encountered a problem, i'm trying to get the index of an element but it keeps returning -1. Here's the code
    Java Code:
    import java.util.ArrayList;
    public class PhoneEntry {
    	String name;
    	String phone;
    public PhoneEntry(String name, String phone) { = name; = phone;
    	public static void main(String[] args){
    	ArrayList<PhoneEntry> theDirectory = new ArrayList<PhoneEntry>();
    	theDirectory.add(new PhoneEntry("Jane","12"));
    	int index = theDirectory.indexOf(new PhoneEntry("Jane","12"));
    I know the list is not empty because it returns a size.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: ArrayList indexOf

    This will never work because the default implementation only checks for reference equality. Your class PhoneEntry must implement the equals() method. And you should usually implement the hashCode() method too. Here is an example --> Object as a Superclass (The Java Tutorials > Learning the Java Language > Interfaces and Inheritance)

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. indexOf(String str) question:
    By jocdrew21 in forum New To Java
    Replies: 4
    Last Post: 04-09-2014, 06:59 PM
  2. IndexOf()?
    By Jeron kahyar in forum New To Java
    Replies: 3
    Last Post: 10-15-2012, 07:27 PM
  3. Help with indexof please...
    By fatabass in forum New To Java
    Replies: 7
    Last Post: 02-07-2012, 09:36 PM
  4. String indexOf
    By ras_pari in forum Advanced Java
    Replies: 3
    Last Post: 10-07-2009, 07:33 AM
  5. Help regarding indexOf
    By gauravj in forum New To Java
    Replies: 1
    Last Post: 07-10-2007, 01:12 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts