gpt4 book ai didi

java - 将元素添加到 ArrayList 的正确位置

转载 作者:行者123 更新时间:2023-11-30 09:49:49 24 4
gpt4 key购买 nike

我有一个自定义的 ArrayList 接口(interface),它扩展了 Comparable 类并且按升序排列。我正在处理的类正在实现此接口(interface)。

我的问题是我需要编辑 add 方法,以便它将一个元素添加到 ArrayList,让 List 保持有序,并确保没有重复项。

用单独的方法完成所有这些很容易,但这是不可能的。我需要一个方法来完成这一切,以便在调用该方法时(只要它不是重复的)将元素添加到正确的位置。

最重要的是,要检查要插入方法的索引的位置,我必须使用从 Comparable 类继承的 compareTo() 方法。唯一的问题是我必须在我正在处理的类中实现我自己的 compareTo() 方法。我已经查看了所有内容,但对于如何针对该特定类(class)进行此操作感到困惑。

到目前为止,这是我的代码:

    public void add(E item) throws IndexOutOfBoundsException {

if (contains(item)) {
throw new IllegalArgumentException("This is a duplicate!");
}
//here is where I need the implementation to add the item to the array, in order

}

然后这是我的 compareTo() 方法:

        public int compareTo(E item) {

if () {
return -1;
}
else if () {
return 1;
}
else {
return 0;

}
}

最佳答案

一种方法是先检查是否

myArrayList.contains(item)

然后如果没有,只需插入并重新排序您的数组:

myArrayList.add(item);
Collections.sort(myArrayList);

请注意,一般来说,如果您想维护一个有序集合而不重复,有比 ArrayList 更好的数据结构。

关于java - 将元素添加到 ArrayList 的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5561100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com