简体   繁体   中英

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

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

You can use java 8 stream:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM