I am writing a program that uses two arrays, one holds int and one holds String. I am using an interface and building a class that implements it. The method in the interface uses a method written like

public void add(E element) throws OverFlowException;

This method is to add an element to one of the arrays depending on what is put in the parameter. My problem is how to differentiate in my class method that implements this method which is which, so I can tell which array the element should add into. My method that implements this is written

public void add(Object element) throws OverFlowException
{

MY CODE HERE.

}

So the question is, how do I identify whether the element is a String or an int when it is passed through the parameter to the implenting method I am writing? I know I have to write an if statement that compares element to String or int, but not sure how to compare the element to the data type. I have only had to write them using the actual value or input in that variable.

Thank you in advance for any help.

No. Write two methods. One that takes a String as an parameter, and one that takes an int as a parameter.

If you feel you must do it this way, then Google for "Java instanceof".

commented: Yep +3
commented: Thank you for your help. Your idea worked using instanceof. +1

Thank you for the help. I fixed it using the instanceof. I couldn't use two methods because it was using generic data types and the actual program would not know what data types were being passed to it. I just knew because my instructor gave us a copy of the client we were to use to run against our program. But its fixed, ty for help.

If you can use instanceof you can use multiple methods. What difference does it make if you use three if statements with instanceof or three overloaded methods? None, except that the overloaed methods version is more flexible, more reliable, and less likely to cause runtime problems. But, hey, more power to you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.