Can I write a for loop that iterates over both collections and arrays?

Can I write a for loop that iterates over both collections and arrays?

Is there a possibility to check if an object is either an array or a collection with one clause? What I am trying to achieve:

Is there a possibility to check if an object is either an array or a collection with one clause? What I am trying to achieve:

Assuming arrays implement Iterable, and assuming the Object foo could be either an array or a collection, I'd like to use a code snippet like this:

if (foo instanceof Iterable) {
  for (Object f : (Iterable) foo) {
    // do something with f
  }
}

Unfortunately, an array cannot be cast to Iterable. Nor does it implement Collection. Are there any other possibilities to handle both in one loop like the above? Instead of -- of course -- using an if-else if-clause and two loops (which wouldn't be nice).

Edit: In response to these answers. I am aware of the isArray() method but in this case the casting in

...
for (Object f : (Iterable) foo) {
...

will fail. That'd a pity and a code redundancy since I would have to use two loops although a foreach-loop works both with Collections and Arrays.

java arrays

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

How to Build a Dynamic Array By Using a Static Array in Java

We all know about the basic data structure, which is Array pretty well. And in java they are static. It means we have to allocate memory for the array ahead of time.

What is an Array in java how to create an Array

What is an Array in java how to create an Array

Convert an Array of Primitives to a List

Learn how to convert an array of primitives to a List of objects of the corresponding type.

Java Core (2020) | Java for beginners | Brush up your Java Skills | Get Hired

In this video we will learn about all the major concepts that come under Java Core . The course is very carefully designed and is made with keeping simplicit...