Doesn’t Arraylist accept Overload Polymorphism?

Asked

Viewed 54 times

-1

I am trying to overload the add method, but apparently this does not work with Arraylists. Confirm?

Métodos:

    public int somar(ArrayList <Classe> classe){...}
    
    public int somar(ArrayList<Filme> filmes){...}
    
    public int somar(ArrayList<Aula> aula){...}
  • I didn’t find documentation most recent but generics have been introduced in the Java language to provide more rigid type checks in compilation time. To implement generics, the Java compiler applies type deletion by replacing all parameters in generic types with Object so the bytecode produced contains only common classes, interfaces and methods and consequently, generics do not generate overhead in running time.

1 answer

0

You cannot do Overload with generic types, type information is removed at runtime (see about type Erasure), therefore the mistake.

You can use typed arrays instead of ArrayList generic, or leave the signature of the generic method.

For example: if your classes extend TipoComum, the signature would stand:

public int somar(ArrayList<? extends TipoComum> lista){...}

In this case you would have a single method instead of one for each subtype of TipoComum.

See also the response of #8679

Browser other questions tagged

You are not signed in. Login or sign up in order to post.