Java passing variable - downcasting

612 views Asked by At

I have a function e.g.

helloworld(list<object> names)

I have the following code :

List<CustomClass> newMe = new ArrayList<CustomClass>();

Now, if i want to pass newMe into helloworld(newMe);. This is not possible because im down casting. How can i overcome this issue? Do i downcast my list to (Object) and then try to upcast it? is there another way? would appreciate an example.

thanks

2

There are 2 answers

4
Luiggi Mendoza On BEST ANSWER

Change the definition of helloworld to

public void helloworld(List<?> names) {
    //method implementation...
}

Take into account that your method won't be able to add or remove elements from the list parameter.

0
eyebleach On

Just use a ? as generic type in your parameter list. Example:

public class Foobar {
    public static void helloworld(List<?> names) {

    }
    public static void main(String[] args) {
        List<CustomClass> newMe = new ArrayList<>();

        helloworld(newMe);
    }
}