PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] how do i create a Method that accepts both String[] and Integer[] in java without method overloading?

 July 20, 2022     arrays, integer, java, methods, string     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing