0

OK so I have the following Object class:

public class IntoleranceFood implements Comparable<IntoleranceFood>{

private int scoreInt;
public String foodName;

public IntoleranceFood(String food, int score) {
    super();
    this.foodName = food;
    this.scoreInt = score;

}

//getters and setters
public String getFood() {
        return foodName;
}
public void setFood(String food) {
        this.foodName = food;
}
public int getScore() {
    return scoreInt;
}
public void setScore(int score) {
        this.scoreInt = score;
}


@Override
public String toString() {
    return "Intolerance Food [Name=" + foodName + ", Score=" + scoreInt + "]";
}

@Override
public int compareTo(IntoleranceFood arg0) {

    return toString().compareTo(arg0.toString());
}

}

And then in my Activity I have created an array for these objects to go into, and filled up the array with "IntoleranceFood" Objects:

int numFoodItemTypes = db.intoleranceFoodItemTypesTotal();
    IntoleranceFood[] foodArray = new IntoleranceFood[numFoodItemTypes];

    Cursor cAllFoodTypes = db.intoleranceFoodTypesList();
    int foodItem = 0;
    do{
        foodArray[foodItem] = new IntoleranceFood(cAllFoodTypes.getString(0), 0);
        foodItem++;
    }while(cAllFoodTypes.moveToNext());

I managed to sort the array by implementing Comparable and the compareTo method in my Object class:

Arrays.sort(foodArray);

But I want to then search the array using binary search, and look for the position in the array where a certain Object with a specific food name (String) resides. But I dont know how to get the following code working, and specifically in terms of:
-binarySearch(Object[] array, Object value)
I don't know what to put in "Object value" so this:

Arrays.binarySearch(foodArray, "Cereal");

Is clearly wrong! But I'm not sure how to search the Object array for an Object containing the String food name "Cereal".

Thanks.


Yes so after the very useful reply below, I realsied what I need to be doing is:

IntoleranceFood searchOb = new IntoleranceFood("Cereal",0);

    int searchIndex = Arrays.binarySearch(foodArray, searchOb);

And that works!

Slab
  • 353
  • 3
  • 14

1 Answers1

1

In my opinion your mistake is

Arrays.binarySearch(foodArray, "Cereal");

because "Cereal" is not the Object you are looking for and your array doesnt contain this object. The second parameter should be an instance of the IntoleranceFood class and "Cereal" is just a property of that class.

For your problem i would use a HashMap or another Map who fits your problem best!

Maybe this article will help you : How to sort a HashMap in Java

Community
  • 1
  • 1
Ra Mon
  • 127
  • 3
  • Ah! Do you know what, you writing it down so logically like that has made me realised, all I need to do is create and instance of my object with the "Cereal" string, and then use that as the second parameter! - IntoleranceFood searchOb = new IntoleranceFood("Cereal",0); Thanks! – Slab Mar 19 '14 at 15:45