David Paulo
David Paulo

Reputation: 433

Check if an instance is either an Array or a Collection in Java

I want to create a method in Java that receives either an array or a collection, it does not matter, because all i do is iterate it. I don't want to create a list from the array because it would impact on the performance of the algorithm and i am really tired of always creating an overloading method for every method which accepts a List. Is there a convenient parent class for both, like "Iterable", or something?

Upvotes: 0

Views: 103

Answers (2)

David Paulo
David Paulo

Reputation: 433

I didn't know about wrapping an array on a list using Arrays.asList method, i thought it would copy the array into a list. Arrays.asList is a O(1) algorithm, as the good people in the comments told me.

Upvotes: 0

ThrawnCA
ThrawnCA

Reputation: 1081

If performance is truly so critical that you cannot afford to wrap an array in an ArrayList, then you need to write separate algorithms for arrays and collections. It's really that simple.

The benefits of polymorphism rest on the assumption that you can afford to trade off a few microseconds to get shorter and more readable code. If you can't afford that, you can't have the convenience.

Upvotes: 2

Related Questions