Search code examples
javaobjectcastingdowncastupcasting

Java passing variable - downcasting


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


Solution

  • 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.