我的通用 sortedArraylist class 不起作用

My generic sortedArraylist class won't work

我正在尝试处理 arrayList 的子class,它将在插入时按升序对类型为 Comparable 的对象进行排序。 class 是通用的,也实现了 Comparable 接口。我的问题是,当我尝试像 (this.add(item)) 添加到 SortedArrayList class 时,我收到一个错误 'java: incompatible types: E cannot be converted to E',但是 item 已经是类型 E.

这是我的代码:

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());
        }
    }
}

又是这个错误

java: incompatible types: E cannot be converted to E

您的通用 SortedArrayList class 将如下所示

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);
    }
} 

请记住在您的用户定义中实现 Comparable 接口 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());
    }
}