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

Time:05-22

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[] -

MyClass.This cannot be referenced from a static context

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

CodePudding user response:

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.

CodePudding user response:

Your premise:

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

… is incorrect.

  • Related