Search code examples
javaarraylist

How to solve a problem with generalized types more correctly


My program has 5 classes:

1 - Abstract class Animal

public abstract class Animal {
}

2, 3 - Classes that extend an abstract class

public class Cat extends Animal implements Comparable<Cat> {
//some logic
}
public class Dog extends Animal implements Comparable<Dog> {
//some logic
}

4 - A class that contains a method for sorting animals. The sorting method must be implemented on the basis of generics. This class must necessarily use a generalized type (this is a strict condition).

public class AnimalOperations {
    public static <T extends Animal & Comparable<T>> void Sort (ArrayList<T> array){
    //sort logic
    }
}

5 - class Main. my problem is related to this class. In this class, I have to fill out an ArrayList that contains cats or dogs. Next, this array must be passed to the sorting method of the AnimalOperations class.

I know that I can solve this problem by creating two different arrays.

ArrayList<Cat> = new ArrayList<>();
ArrayList<Dog> = new ArrayList<>();

But I want to see if I can solve this problem by creating only one ArrayList() in the Main class. I tried this:

ArrayList<Animal> animal = new ArrayList<>(List.of(new Cat(), new Cat(), new Cat()));

But then when passing it to the sort method of the AnimalOperations class, I see an error "Required type: ArrayList T Provided: ArrayList Animal".

I also tried to create an ArrayList based on a generic in the Main class

public static <T extends Animal & Comparable<T>> void main(String[] args) {
    ArrayList<T> animal = new ArrayList<>(List.of(new Cat()));
}

But with this initialization, I see an error: "Required type: ArrayList T Provided: ArrayList Cat ".


Solution

  • Thank you for your question!

    In my opinion this becomes way more easier when you try to use your sort method without generics like this:

    public static void sort(ArrayList<Animal> array) {
    // Some logic
    }
    

    (Also I saw you are having a upper case character in the beginning of your method name. You should use "sort" and not "Sort".)

    If you still get an error, it is always possible to cast the class to the specific one like this:

    public static void sort(ArrayList<Animal> array) {
      for (Animal animal : array) {
        if (animal instanceof Cat) {
          Cat cat = (Cat) animal;
          // Do stuff with cat
        } else if (animal instanceof Dog) {
          Dog dog = (Dog) animal;
          // Do stuff with dog
        }
      }
    }
    

    I hope this helps!