2

I just started learning about the ArrayList class in Java. I have the following code below testing out the ArrayList class and it's methods:

import java.util.ArrayList;

public class NewArrayList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<String> myList = new ArrayList<String>();

        String s = new String();
        myList.add(s);
        String b = new String();
        myList.add(b);

        int theSize = myList.size();
        System.out.println("ArrayList size: " + theSize);

        boolean isTrue = myList.contains(s);
        System.out.println(isTrue);

        int whereIsIt = myList.indexOf(s);
        System.out.println(whereIsIt);
        int whereIsIt2 = myList.indexOf(b);
        System.out.println(whereIsIt2);

    }

}

The indexOf method shows whats the index of an object. So since I added two objects, s and b to the myList ArrayList object reference, it should have 2 objects inside the index. The output of whereIsit and whereIsit2 is both 0. Shouldn't it be 0 1??

3 Answers 3

10

You're adding two String objects with the same value (empty string) to the list.

So your list looks like

["", ""]

You're then invoking the equivalent of indexOf(""), where indexOf(..) uses the Object#equals(Object) method to compare objects. The first element in the list is equal to "", so that index is returned.

Sign up to request clarification or add additional context in comments.

Comments

0

Here you just create two objects and that has no value so it will be treated as empty string. So the Indexof will returns the first occurence of the given object.

If you assign different values to s and b then result what you are expecting that will get. Please try with below code.

    String s = "String1";
    myList.add(s);
    String b = "String2";
    myList.add(b);

    int whereIsIt = myList.indexOf(s);
    System.out.println(whereIsIt);
    int whereIsIt2 = myList.indexOf(b);
    System.out.println(whereIsIt2);

Comments

0

Please read method description in the docs before using http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html

int     indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1   if    this list does not contain the element.  

and

public int lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.