Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

public class MyClass extends ArrayList<String> {

    public static void main(String[] args) {
        MyClass arrayList1 = new MyClass();
        arrayList1.add("Zebra");
        arrayList1.add("Giraffe");
        arrayList1.add("Bison");
        arrayList1.add("Hippo");
        arrayList1.add("Elephant");

        MyClass arrayList2 = (MyClass) arrayList1.clone();
        MyClass arrayList3 = (MyClass) arrayList1.clone();

        System.out.println(arrayList1);
        System.out.println(arrayList2);
        System.out.println(arrayList3);

        arrayList1.removeRange(0, 3);
        arrayList2.removeRange(3, 5);
        arrayList3.removeRange(2, 4);

        System.out.println(arrayList1);
        System.out.println(arrayList2);
        System.out.println(arrayList3);
    }
}

Output –

[Zebra, Giraffe, Bison, Hippo, Elephant]
[Zebra, Giraffe, Bison, Hippo, Elephant]
[Zebra, Giraffe, Bison, Hippo, Elephant]
[Hippo, Elephant]
[Zebra, Giraffe, Bison]
[Zebra, Giraffe, Elephant]

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MyClass.This cannot be referenced from a static context

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

>Solution :

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

public class MyClass<T> extends ArrayList<T>

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

MyClass<String> arrayList1 = new MyClass<>();

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading