0

so I need some help in understanding this "syntax" or way of writing a for loop

for(random : random1) {

now is there a way to write this in the "easier" way what I mean is:

for(int i=0; random.lenght i++) {

I'm interested in how to "rewrite" this in this concrete example

public Merchandise findMerchandise(String name) {
    Merchandise found = null;
    for(Merchandise the : merchandise) {
        if(the.getArticle().getName().equals(name)) {
            found = the;
        }
    }
    return found;
}
nafas
  • 5,283
  • 3
  • 29
  • 57
arhzzz
  • 5
  • 4

1 Answers1

0

Yes, you can write it using a basic for loop:

// If it's a List<Merchandise>
for (int i = 0; i < merchandise.size(); ++i) {
  Merchandise the = merchandise.get(i);
  // Rest of loop body.
}

or

// If it's a Merchandise[]
for (int i = 0; i < merchandise.length; ++i) {
  Merchandise the = merchandise[i];
  // Rest of loop body.
}

But this isn't easier.

For one thing, it's more verbose: you've got to declare a whole bunch of things (the variable, the size check, the get of the item).

For another, it's more error-prone: you've got to make sure when write all the bits of the loop (the size check, the increment, the get etc) that you reference the right list and right index variable.

For yet another, it's less efficient on lists that don't support random access lookup (for example LinkedList).

Want more? You've got to change the code depending on whether it's a List or an array, and you can't use it for non-indexable collections e.g. Set.

Stick with what you've got.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243