SammyHD
SammyHD

Reputation: 49

How to search for certain strings within an Arraylist

Firstly I would like to thank the community here on their help so far.

In a method I have to write the instructions state that I have to find a Fragment whose name includes key.

ArrayList<Fragment> collage;

Now, i have experiment with indexOf and .contains in this method, but I cannot figure it out. I figure you have to make a string with the value "key"

String str = "key";

Then use indexOf to find the index at which "key" is found? is this right, or does indexOf work only in strings? Can anyone help point me in the right direction here? Thanks in advance.

Upvotes: 0

Views: 125

Answers (2)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

You can do it with a simple for loop:

ArrayList<Fragment> collage = new ArrayList<String>();
//...
for (Fragmenttmp: collage){
    if (tmp.name.equals(key))
        //do something
}

However I suggest you to use a HashMap :

HashMap<String, Fragment> collage = new HashMap<String, Fragment>();
//...
collage.get(key);

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68905

In List all elements are stored in the insertion order. So in order to get that order you can use indexOf() method which returns the index of the first occurrence of the specified element in this list.To check whether a particular String exists in the List or not you use contains(). It simply returns a boolean value and has nothing to do with order/index or number of time element occurs in the List.

Upvotes: 1

Related Questions