Reputation: 91
I couldn't really come up with the words as to how to describe my question in the title. What I'm trying to accomplish is something like this: (Pseudo code)
SuperClass[] superArray = new SuperClass[];
// work on superArray
// ...
SubClass[] subArray = superArray.asAnArrayOfSubClass();
` Is something like this possible?
Upvotes: 3
Views: 113
Reputation: 7504
There are restrictions that your subclass should match super class wrt properties and methods and you are only overriding those.
Below is an example of how you could do this using streams API.
Number[] array = new Number[]{12, 20, 30, 40};
List<Integer> list = Arrays.stream(array)
.map(e -> (Integer) e)
.collect(Collectors.toList());
System.out.println(list.toArray());
Upvotes: 0
Reputation: 131346
You cannot add members : methods or fields to an array. So no, it is not possible :
SubClass[] subArray = superArray.asAnArrayOfSubClass();
To define a behavior for an array, instead create a method where you pass the array :
SubClass[] doThat(SuperClass[] superArray){
....
}
Even if conceptually, a type should not know its subtypes, if it is your requirement it is valid to convert manually an array of a specific type to an array of a subclass of this specific type.
For example, you can have employees stored in an array that at time are promoted as managers. This method could do this conversion :
Manager[] promote(Employee[] employees){
Manager[] managers = new Manager[employees.length];
for (int i=0; i<employees.length; i++){
Employee e = employee[i];
managers[i] = new Manager(....);
}
return managers;
}
Upvotes: 1
Reputation: 197
Casting to subclasses is a code smell, and probably you should reconsider your design. Also try to use a java collection api (Iterable, Collection, List), with generics, and not primitive arrays, which you can subclass adding your own methods like the example below:
public interface IteratorWithIndex<T> extends Iterator<T> {
int index();
}
Upvotes: 0
Reputation: 121998
No. Not possible. Because not every Parent is a Child. The reverse is possible as Every child is a Parent.
See the below example.
Object[] supers = new Object[5];
Integer[] childs = supers // Errrr.. No I have Strings, Doubles too
But the reverse is possible
Integer[] childs = new Integer[5];
Object[] supers = childs // Ok, I can hold any object.
Upvotes: 0