0

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.

5
  • You can't do that directly in a List; at least not with Java 7. With Java 8 you could use .stream().allMatch(). With Java 7 you have to loop and extract; or if you use Guava, Iterables.filter() through a Predicate Commented Apr 9, 2014 at 11:18
  • You will not be able to find a String in a list of Fragments. Commented Apr 9, 2014 at 11:18
  • "or does indexOf work only in strings" ... it uses the equals method, so it does not only work on Strings. However, a Fragment will most likely not be equal to a String. Commented Apr 9, 2014 at 11:20
  • Maybe a little more code would be helpful. Could you add the code for the Fragment? Commented Apr 9, 2014 at 11:25
  • Just iterate the ArrayList<Fragment> then on each iteration check your string with .equals() so you will get appropriate result. Commented Apr 9, 2014 at 11:27

2 Answers 2

1

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.

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

1 Comment

Are stored in insertion order. That is an important distinction.
1

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);

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.