Win a copy of hapi.js in Action this week in the HTML, CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Changing my index code Loop from String[] to Arraylist

 
Sean Reliford
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code gets the indexes of the occurrences in the test string and stores them in the output arraylist. How can I do the same thing with an arraylist in the words string array? Can this be done and functionally do the same thing?



import java.util.ArrayList;

public class arr {
    ArrayList<String> output = new ArrayList<String>();

    public arr() {
        String test = "I like the Disney Starwars films a lot. But the OG trilogy is still the best.”;
        String[] words = {"a lot", "OG",”the best”};//------- Replaces this with arraylist?
        for (int j = 0; j < words.length; j++) {
            for (int i = -1; (i = test.indexOf(words[j], i + 1)) != -1; ) {
                String o = ("" + i);
                output.add(o);
            }
        }
    }
}

 
Junilu Lacar
Sheriff
Posts: 9338
96
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags (←click that link) when posting code.
 
Junilu Lacar
Sheriff
Posts: 9338
96
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can replace the array with a list. Look at the java.util.List API documentation for methods you can use to iterate over its elements.
 
Rob Spoor
Sheriff
Posts: 20800
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sean Reliford wrote:                String o = ("" + i);

That's actually quite inefficient. It's equivalent to String o = new StringBuilder().append("").append(i).toString();. In that line, appending i will call Integer.toString(i), which is what you can do directly:
And in case you don't know if such a static toString method exists, you can always call String.valueOf, which has several overloads and does the exact same thing.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!