I'm continuously having problems with this computer Assignment. Essentially we have to edit the two add methods of ArrayList, so that it will allow us to store integers going from highest to lowest.
Here is the code my professor provided to test our add methods:
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();
}
}
Here are my two add methods:
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();}
}
}}
Now my program compiles but the amount of integers I have stored in the arraylist is way to few. The array list should be storing 20+ integers. I know that my boolean add method is the problem.
Any help you guys could offer me is as always much appreciated.