【发布时间】:2016-02-23 22:05:57
【问题描述】:
所以我在做这个家庭作业时遇到了麻烦。本质上,我们必须创建扩展 java.util.ArrayList 的类 SortedArrayList,并覆盖 ArrayList 的默认添加方法,以便我们可以维护从最低到最高的整数排序列表。
这是我的教授给班级测试我们方法的代码:
package Asg3;
import java.util.ArrayList;
import myUtil.SortedArrayList;
public class Asg3 {
public static void testInteger() {
SortedArrayList<Integer> sorted= new SortedArrayList<Integer>();
for (int i=0;i<20;i++) {
sorted.add((int)(Math.random()*1000));
}
int bad=0;
for (int i=0;i<20;i++) {
try {
sorted.add((int)(Math.random()*1000)%sorted.size(),(int)(Math.random()*1000));
} catch (IllegalArgumentException e) {
System.out.print(".");
bad++;
}
}
System.out.println("\nsize: "+sorted.size()+" bad insertions: "+bad);
System.out.println(sorted.toString());
}
}
public static void main(String[] args) {
testInteger();
}
}
到目前为止,这是我要重写的 add 方法,以便它们维护一个排序的数组列表。
package myUtil;
public class SortedArrayList<T extends Comparable<T>>extends java.util.ArrayList<T>
{
public SortedArrayList()
{
}
public SortedArrayList(int capacity)
{
}
@Override
public boolean add(T item)
{
int index=this.size()-1;
//checks to see if item is greater than or equivalent to the last element in the list
if(item.compareTo(this.get(index))>=0||this.get(index)==null)
{
//creates a new element at the end of the list and sets the value of item to it
this.set(index+1,item);
}
return true;
}
@Override
public void add(int i, T item)
{
//check to see if item is greater than the previous element, and less than the next element
if(item.compareTo(this.get(i-1))<0 && item.compareTo(this.get(i+1))>0)
this.set(i, item);
}
}
我收到一条错误消息:线程“主”ArrayIndexOutOfBoundsException 中的异常:-1
在 myUtil.SortedArrayList.add(SortedArrayList.java:21)
SortedArrayList 的第 21 行是 boolean add 方法中的 if 语句。
抱歉,如果这似乎是一个愚蠢的问题,我的教授在过去 2 天的办公时间内没有出现,所以我真的没有其他地方可以寻求帮助。一如既往地感谢大家提前回复。
【问题讨论】:
-
那么,当你的列表最初是空的,然后你添加一个元素时会发生什么?
-
更新您的代码并添加带有名称的完整类,以便我将完全相同的代码复制粘贴到我的 IDE 上运行并为您解决问题。
-
@Waqas Ahmed,好的,只需复制并粘贴完整的代码,感谢您提出的任何解决方案。
-
(旁注:这是一个非常令人讨厌的任务,因为它告诉你故意违反
List合同。) -
@LouisWasserman 你说的违反清单合同是什么意思?我只是好奇而已。