1

Let's say I have an object like:

public class Fruit{

private String name;
private int quantity;

    Fruit(){}
    Fruit(String name, int quantity){
        this.name = name;
        this.quantity= quantity;
    }

    public int getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And I want to sort an array full of Fruit objects alphabetically by name. My initial thought, Arrays.sort(a.getName()); wouldn't work, because .getName() only works on individual objects. One idea I had was put all the names into an array, sort those alphabetically, then run a loop to sort the objects using this list, but that seems absurdly cumbersome.

Any ideas? As you can tell, I'm very new to working with objects in this manner.

1
  • suppose this post has the solution for your issue. suppose you need to implement Comparator. This may be a good place to refer. Commented Apr 21, 2017 at 0:13

3 Answers 3

3

Either you make your Fruit class Comparable by implementing the compareTo method, or you provide a custom Comparator to the Arrays.sort method:

Arrays.sort(fruits, Comparator.comparing(Fruit::getName));

This uses the Comparator.comparing method.

Sign up to request clarification or add additional context in comments.

1 Comment

Ooooh, I like this.
1

I recommend you redefine your Fruit class to implement Comparable<Fruit> so that you can easily sort a Fruit[] by each elements' respective name field:

public class Fruit implements Comparable<Fruit> {
    // Code here...

    @Override
    public int compareTo(Fruit fruit) {
        return name.compareTo(fruit.name);
    }
}

Now, you can call Arrays#sort on Fruit[] and it will sort them lexicographically by name.

1 Comment

Very smart and clean solution
1

You don't need to make your Fruit class implement Comparable<Fruit>; you can do it by passing a custom Comparator to the array, like this:

Array<Fruit> sortedArray = sort(fruitArray, new Comparator<Fruit>() {
   public int compare(Fruit left, Fruit right) {
       return left.name.compareTo(right.name);
   }
   public int equals(Object obj) { return 0; /* you can ignore this */ }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.