Sorry for the newbie question, I'm used to C# so my Java framework knowledge is not so good.
I have a couple of arrays:
int[] numbers = new int[10];
String[] names = new String[10];
//populate the arrays
Now I want to make a generic function which will print out the values in these arrays, something like the following (this should work in C#)
private void PrintAll(IEnumerable items)
{
foreach(object item in items)
Console.WriteLine(item.ToString());
}
All I would have to do now is to
PrintAll(names);
PrintAll(numbers);
How can I do this in Java? What is the inheritance tree for the array in Java?
Many thanks
Bones
Inheriting from Array<T> If a browser supports iterables, then all built-in collections are implemented as iterables. In particular, it is often very useful to inherit from arrays because JavaScript has a lot of built-in operations to process arrays that will be automatically inherited by all array subclasses.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value). When you pass an array to other method, actually the reference to that array is copied.
Every class in Java IS an Object. They behave like Objects, they can be added to collections of type Object, they can use any method defined in Object. So, YES, everything (except primitives) inherit from Object in Java. EDIT:Java takes the approach of "Everything is an Object".
Arrays only implement Serializable
and Cloneable
in Java1; so there is no generic way to do this. You'd have to implement a separate method for each type of array (since primitive arrays like int[]
cannot be cast to Object[]
).
But in this case, you don't have to because Arrays
can do it for you:
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(numbers));
This will yield something like:
[Tom, Dick, Harry] [1, 2, 3, 4]
If that's not good enough, you're stuck having to implement a version of your method for each possible array type, like Arrays
does.
public static void printAll(Object[] items) {
for (Object o : items)
System.out.println(o);
}
public static void printAll(int[] items) {
for (int i : items)
System.out.println(i);
}
public static void printAll(double[] items) {
for (double d : items)
System.out.println(d);
}
// ...
Note that the above only applies to arrays. Collection
implements Iterable
, so you can use:
public static <T> void printAll(Iterable<T> items) {
for (T t : items)
System.out.println(t);
}
1 See JLS §10.7 Array Members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With