theejazz
theejazz

Reputation: 41

How to iterate over ArrayLists of different objects with a single method?

I am trying to iterate over two ArrayList fields of different types. While I could write methods for each type, is there a way to iterate over them with only a single method? I can't quite seem to figure out if it is possible to pass on a field as a method argument. In the below code, the method iteratePhrase() is supposed to print all elements in either of the ArrayLists. In it, [...] signifies either numbers or letters.

import java.util.ArrayList;
import java.util.List;

public class Phrase {
    private List<Number> numbers;
    private List<Letter> letters;

    public Phrase() {
        numbers;
        letters;
    }

    public void iteratePhrase() {
        for (int i=0; i<[...].size(); i++)
            System.out.println([...].get(i));
    }
}

Upvotes: 0

Views: 72

Answers (3)

anon
anon

Reputation: 357

You could make both numbers and letters extend a common class, for example IterableObject.

Then, iterate like this

public void iteratePhrase(List<IterableObject> l) {
    for (int i = 0; i < l.size(); i++) {
        System.out.println(l.get(i));
    }
}

or this

public void iteratePhrase(List<IterableObject> objects) {
    for (IterableObject object : objects) {
        System.out.println(object);
    }
}

However, iteratePhrase function will only accept objects, that extend IterableObject, unlike answer above with generics.

Upvotes: 1

Idan Str
Idan Str

Reputation: 614

You can use java 8 stream:

public <T> void iteratePhrase(List<T> al) {
   al.stream.forEach(System.out::println);
}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201419

You could make iteratePhrase generic, that is make it take a List<T>; like

public <T> void iteratePhrase(List<T> al) {
    for (int i = 0; i < al.size(); i++) {
        System.out.println(al.get(i));
    }
}

You could also use a for-each loop like,

for (T t : al) {
    System.out.println(t);
}

In either case, you would call

iteratePhrase(numbers);

and

iteratePhrase(letters);

Upvotes: 3

Related Questions