我的泛型SorterDarrayList类不起作用

qni6mghb  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(335)

我正在尝试处理arraylist的一个子类,它将在插入时按升序对类型相似的对象进行排序。这个类是泛型的,也实现了可比较的接口。我的问题是,当我尝试添加到sortedarraylist类(this.add(item))时,我收到一个错误“java:不兼容类型:e不能转换为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
sr4lhrrt

sr4lhrrt1#

您的泛型SorterDarrayList类将如下所示

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

记住在用户定义的类中实现可比较的接口

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

相关问题