Issue
Let's say you have an integer array and a string array. How can you write a SINGLE method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays. NOTE.. I cannot use method overloading. Any idea to how to go about this?
Solution
The only way I see is
public void print(Object o) {
if (o instanceof String[]) {
System.out.println(Arrays.toString((String[]) o));
}
else if (o instanceof int[]) {
System.out.println(Arrays.toString((int[]) o));
}
}
But it's absolutely ugly. You should have two different methods.
If what you have is an Integer[]
(instead of an int[]
), then it's simpler, and OK:
public void print(Object[] o) {
System.out.println(Arrays.toString(o));
}
Answered By - JB Nizet Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.