Richard Taylor
Richard Taylor

Reputation: 2752

Is there a 'superclass' for Iterable and a regular array?

I'm using an enhanced for loop, and it looks something like this:

public void addItems (Iterable<Item> items) {
    for (Item item : items) {
        addItem(item);
    }
}

public void addItems(Item[] items) {
    for(Item item : items) {
        addItem(item);
    }
}

Using the Iterable allows me to use List et al., but I have to have a separate method for regular arrays. Is there some way to combine this (without using reflection, or increasing line count, or creating garbage), so I don't have to duplicate code?

Upvotes: 1

Views: 133

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

You could overload the method (Preferred)

public void addItems(Item[] items) {
   addItems(Arrays.asList(items));
}

or convert to a List each time you call the method.

addItems(Arrays.asList(new int[]{1,2,3}));

The second method is less than optimal. As Sticky has mentioned:

I'd imagine there's more duplication with Arrays.asList all over the place rather than the 3 lines in my class.

Upvotes: 4

jtahlborn
jtahlborn

Reputation: 53694

public void addItems(Item[] items) {
    addItems(Arrays.asList(items));
}

Upvotes: 5

Related Questions