Reputation: 3
Im currently working on a class that includes a method "add" that adds my specific object to my ArrayList which is a field instantiated in my constructor. The purpose is to obviously add the object to the ArrayList but at the same time it adds the object to the position to where the ArrayList is constantly sorted. The objects are being compared by a String that is received from an accessor method within its class called getCompany(). I'm having trouble understanding how I would go about doing this. My experimental code follows:
public class WeeklyOrders {
private List<DistributionOrder> orders;
public WeeklyOrders(){
orders= new ArrayList<DistributionOrder>();
}
public void add(DistributionOrder dOrder){
int maxPos=0;
int minDiff=0;
for(int i=0;i<orders.size();i++){
String comp=orders.get(i).getCompany();
int diff=comp.compareTo(dOrder.getCompany());
if(diff<minDiff){
minDiff=diff;
maxPos=i;
}
}
orders.add(maxPos,dOrder);
}
public String toString(){
String s="";
for(int i=0;i<orders.size();i++){
s=s+orders.get(i).getCompany()+"\t";
}
return s;
}
}
Upvotes: 0
Views: 77
Reputation: 100169
You are using compareTo
method incorrectly. You should not compare it return values with each other: the only sane usage of compareTo
result is to compare it with zero. It returns any negative number if this element is less than passed element or any positive number if this element is bigger than passed one. Probably you wanted something like this:
int maxPos=-1;
for(int i=0;i<orders.size();i++){
String comp=orders.get(i).getCompany();
int diff=comp.compareTo(dOrder.getCompany());
if(diff<0){
maxPos=i;
} else break; // no need to continue iterating list after that
}
orders.add(maxPos+1,dOrder);
Note that you should carefully think about corner cases: what will occur if dOrder
should become very first and very last element of the orders
.
Finally note that given the fact that the list is always sorted, you may consider using Collections.binarySearch()
method with custom comparator:
int maxPos = Collections.binarySearch(orders, dOrder,
Comparator.comparing(DistributionOrder::getCompany));
if(maxPos < 0) maxPos = - maxPos - 1;
orderds.add(maxPos, dOrder);
This would be faster.
Upvotes: 2