Skip to content
Advertisement

How to use generics for type safety while using `removeRange` method of ArrayList

Since the method – removeRange(int startIndex, int ) is protected, we need to use it in a class extending ArrayList. Below is my code –

JavaScript

Output –

JavaScript

Now to use type safety I need to write – MyClass<String> extends ArrayList<String> but doing so gives error in main method of String[]

MyClass.This cannot be referenced from a static context

So how is it possible to use generics in removeRange method of ArrayList?

Advertisement

Answer

The way to make MyClass able to store objects of any type, not just String is to introduce a type parameter T which fills in for the type. The declaration will then be

JavaScript

But then, you have to specify what T is when you declare a MyClass variable. This means you’ll need to change your variable declarations and initialisations to things like

JavaScript

which tells the compiler what type to use in place of T.

Advertisement