我不断遇到此计算机赋值问题。实质上,我们必须编辑ArrayList的两个添加方法,以便它可以让我们存储从最高到最低的整数。需要帮助使用arrayList排序数字
这里是我的教授提供测试我们添加方法代码:
package Asg3;
import java.util.ArrayList;
import myUtil.SortedArrayList;
/**
* Don't modify any of the following codes.
*
* 2/14/2016
*
* @author Chung-Chih Li
*/
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();
}
}
这里是我的两个添加方法:
package myUtil;
public class SortedArrayList<T extends Comparable<T>>extends java.util.ArrayList<T>
{
public SortedArrayList()
{
super();
}
public SortedArrayList(int capacity)
{
super();
}
@Override
public boolean add(T item)
{
if(this.size()!=0)
{
int index=this.size()-1;
//tests to see if item is greater than the last index and if so places it there
if(item.compareTo(this.get(index))>=0)
{
super.add(item);
}
else
{//tests to see at what index other than the last index, would be appropriate to place the item in.
for(int i=1; i<this.size()-1;i++)
{
if(item.compareTo(this.get(i-1))<=0 && item.compareTo(this.get(i+1))>=0)
{super.add(i,item);
return true;}
else
continue;
}//fix add method
}
}
else
{super.add(0, item);}
return true;
}
@Override//fix add method
public void add(int i, T item)
{
if(i==0)
{
if(item.compareTo(this.get(i))==0&&item.compareTo(this.get(i+1))>0)
{
super.add(i,item);
}
}
else
{
try{
if(item.compareTo(this.get(i-1))<0 && item.compareTo(this.get(i+1))>0)
super.add(i, item); }
catch(IndexOutOfBoundsException e){throw new IllegalArgumentException();}
}
}}
现在我的程序编译,但整数I的量已经存储在arraylist是少数几个。数组列表应该存储20个以上的整数。我知道我的布尔添加方法是问题。
任何帮助你们可以为我提供的是一如既往的赞赏。
调试器是你的朋友!浏览你的代码,看看发生了什么。 –