• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Changing my index code Loop from String[] to Arraylist  RSS feed

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

 
Sheriff
Posts: 12530
206
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac 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: 12530
206
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac 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.
 
Sheriff
Posts: 21503
96
Chrome Eclipse IDE Java Spring Ubuntu VI Editor 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!