Export (0) Print
Expand All

ArrayList.indexOf Method

Visual Studio 2005

Provides the index of an element in a ArrayList object.

Package: java.util

Assembly: vjslib (in vjslib.dll)


public int indexOf(
    java.lang.Object e);

Parameters

e

The element whose index is to be returned.

The index of an element in ArrayList, or -1 if the element does not exist.

The following example creates an ArrayList containing various breeds of dogs. It then tries to determine where a certain dog is located within the ArrayList.

// arraylist_indexof.jsl

import java.util.*;

public class Program
{
    public static void main(String[] args)
    {
        // Fill an ArrayList with various breeds of dogs on exhibit
        // at a dog show.
        ArrayList dogs = new ArrayList();

        Dog fido = new Dog("Golden Retriever");
        Dog fluffy = new Dog("Poodle");
        Dog shadow = new Dog("Basenji");
        Dog miki = new Dog("Yorkshire Terrier");

        dogs.add(fido);
        dogs.add(fluffy);
        dogs.add(shadow);
        dogs.add(miki);

        // Where are the barkless dogs?.
        int stageNumber = dogs.indexOf(shadow);
        if (stageNumber > 0)
        {
            System.out.println("Shadow the basenji is on stage " +
                stageNumber);
        }
        else
        {
            System.out.println("There are currently no basenjis " +
                "being shown.");
        }
    }
}

public class Dog
{
    public Dog(String breed)
    {
        this.breed = breed;
    }

    public String toString()
    {
        return breed;
    }

    private String breed;
}

/*
Output:
Shadow the basenji is on stage 2
*/

Community Additions

ADD
Show:
© 2014 Microsoft