Search code examples
javagenericsgeneric-programmingcomparable

My generic sortedArraylist class won't work


I'm trying to work on a subclass of arrayList which will sort objects that are of type Comparable in ascending order upon their insertion. The class is generic and implements the Comparable interface too. My problem is that when I attempt to add to the SortedArrayList class like (this.add(item)) I receive an error 'java: incompatible types: E cannot be converted to E', however item is already of type E.

Here is my code:

import java.util.ArrayList;

public class SortedArrayList<E> extends ArrayList<E> {

    public <E extends Comparable<E>> void insert(E item){
        if(this.size() == 0){
            this.add(item); //Error is here.
            return;
        }
        for (int i = 0; i < this.size(); i++){
            int comparison = item.compareTo((E) this.get(i));
            if (comparison < 0){
                this.add(i, item); //Error is here.
                return;
            }
            if(comparison == 0) {
                return;
            } 
        }
        this.add(item); //Error is here.
    }

    public static <E> void main(String[] args) {
        User louie = new User("Louie", "Franchino");
        User Alarna = new User("Alarna", "Eke");
        User freddie = new User("Freddie", "Franchino");


        SortedArrayList<User> list = new SortedArrayList<>();
        list.insert(louie);
        list.insert(Alarna);
        list.insert(freddie);

        for (Object item : list) {
            System.out.println(item.toString());
        }
    }
}

And here is the error again

java: incompatible types: E cannot be converted to E

Solution

  • Your generic SortedArrayList class will look like this

    public class SortedArrayList<E extends Comparable> extends ArrayList<E> {
    
        public void insert(E e) {
            this.add(e);    
            int lastIndex = 0;    
            for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
                this.set(lastIndex, this.get(lastIndex-1));
            }
           this.set(lastIndex,e);
        }
    } 
    

    Just remember to implement Comparable interface in your user defined classes

    public class User implements Comparable<User> {
    
        private String name;
        private Integer id;
    
        public User(String name, Integer id) {
            this.name = name;
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
    
        @Override
        public int compareTo(User user) {
            return this.getName().compareTo(user.getName());
        }
    }