1

我正在尝试使用 Java 中的 ArrayList 按名称、颜色和重量对 Fruit 类的特征进行排序。在创建 Fruit 类的实例之前,名称、颜色和重量都从用户以字符串形式在一行中读入。然后我需要将 Fruit 对象添加到 ArrayList,并按照我之前提到的顺序对它们进行排序。换句话说,首先按名称按字母顺序排列,然后按颜色排列,最后按重量排列。

我不完全确定如何从 ArrayList 类中实现 sort() 方法。你对我有什么建议吗?或者也许有任何教程可以建议我在哪里可以提高我对 sort() 和 ArrayLists 的理解?

代码如下。

谢谢!

import java.util.*;

/**creates instances of the Fruits class, and stores the
* resulting objects in an array which can be ordered
* firsting alphebetically by name, then by colour, and
* finally, in ascending order by weight
**/
public class Driver
{
   public static void main(String[]args)
   {
      Scanner s = new Scanner(System.in);
      int input = 0;

      ArrayList fruitInfo = new ArrayList();

      do
      {
         System.out.println("Enter option: (1) add fruit (2) quit:");
         input = s.nextInt();
         s.nextLine();

         switch(input)
         {
            case 1:{ 
                     System.out.println("Enter name, colour and mass in kg separated by a `enter code here`space");
                     String in = s.nextLine();
                     String[] temp = in.split(" ");

                      //create a new instance of the fruit class and add it to the `enter code here`<ArrayList> {@link ArrayList}, fruitInfo
                     fruitInfo.add(new Fruit(temp[0], temp[1], temp[2]));
                      break;
                   }

            case 2:{
                     break;
                    }

            default: System.out.println("Input incorrect. Try again.");
         }
      }
      while(input!=2);
   }
}

/* Class Fruits
* a class modelled on the characteristics of fruit
* each fruit has a name, colour and mass, which are
* stored as <Strings>
**/

public class Fruit
{
private String name;
private String col;
private String kg;

/* Constructor
* constructs an instance of the Fruit class
* using user defined characteristics
**/

public Fruit(String name, String colour, String mass)
{
   this.name=name;
   col=colour;
   mass=kg;
} 
}
4

4 回答 4

1

让您的 Fruit 类实现 Comparable 并在其中实现您的比较逻辑

public class Fruit implements Comparable<Fruit>
...

   public int compareTo(Fruit otherFruit) {
   ... your compare logic here ....
   }

}

然后你可以用 Collections.sort(myList); 对你的列表进行排序。

于 2013-09-13T16:05:46.130 回答
1

你应该实现一个比较器

public class FruitComparator implements Comparator<Fruit> {
    @Override
    public int compareTo(Fruit f1, MyObject f2) {
       if(!f1.getName().equals(f2.getName())) return f1.getName().compareTo(f2.getName()));
       if(!f1.getColor().equals(f2.getColor)) return f1.getColor().compareTo(f2.getColor()));
       if(!f1.getWeight().equals(f2.getWeight())) return f1.getWeight().compareTo(f2.getWeight()));

    }
}

现在您可以将该Collections.sort方法与您的新比较器一起使用:

Collections.sort(fruitInfo, new FruitComparator());
于 2013-09-13T16:08:04.857 回答
0

如果你的 Fruit 类实现了 java Comparator Interface(在 google 上查找),这可以通过使用 Collections.sort 来完成。我试图将其实现到您的代码中:

import java.util.*;

/**creates instances of the Fruits class, and stores the
 * resulting objects in an array which can be ordered
 * firsting alphebetically by name, then by colour, and
 * finally, in ascending order by weight
 **/
public class Driver
{
    public static void main(String[]args)
    {
        Scanner s = new Scanner(System.in);
        int input = 0;

        ArrayList fruitInfo = new ArrayList();

        do
        {
            System.out.println("Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:");
            input = s.nextInt();
            s.nextLine();

            switch(input)
            {
                case 1:{
                    System.out.println("Enter name, colour and mass in kg separated by a `enter code here`space");
                    String in = s.nextLine();
                    String[] temp = in.split(" ");

                    //create a new instance of the fruit class and add it to the `enter code here`<ArrayList> {@link ArrayList}, fruitInfo
                    fruitInfo.add(new Fruit(temp[0], temp[1], temp[2]));
                    break;
                }

                case 2:{
                    break;
                }
                case 3:
                    Collections.sort(fruitInfo, Fruit.FruitNameComparator);
                    for(Object fruit:fruitInfo) {
                        System.out.println(fruit);
                    }
                    break;
                case 4:
                    Collections.sort(fruitInfo, Fruit.FruitKgComparator);
                    for(Object fruit:fruitInfo) {
                        System.out.println(fruit);
                    }
                    break;
                default: System.out.println("Input incorrect. Try again.");
            }
        }
        while(input!=2);
    }
}

和水果类:

import java.util.Comparator;

public class Fruit implements Comparator<Fruit>
{
    private String name;
    private String col;
    private String kg;

/* Constructor
* constructs an instance of the Fruit class
* using user defined characteristics
**/

    public Fruit(String name, String colour, String mass)
    {
        this.name=name;
        col=colour;
        kg=mass;
    }

    public static Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>() {
        @Override
        public int compare(Fruit o1, Fruit o2) {
            return o1.name.compareTo(o2.name);
        }
    };
    public static Comparator<Fruit> FruitColComparator = new Comparator<Fruit>() {
        @Override
        public int compare(Fruit o1, Fruit o2) {
            return o1.col.compareTo(o2.col);
        }
    };
    public static Comparator<Fruit> FruitKgComparator = new Comparator<Fruit>() {
        @Override
        public int compare(Fruit o1, Fruit o2) {
            return o1.kg.compareTo(o2.kg);
        }
    };

    @Override
    public int compare(Fruit o1, Fruit o2) {
        return o1.name.compareTo(o2.name);
    }
    public String toString() {
        return "Name: " + name + " Colour: " + col + " Weight: " +kg;
    }
}

这里是一个示例输出:

Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:
1
Enter name, colour and mass in kg separated by a `enter code here`space
a b c
Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:
1
Enter name, colour and mass in kg separated by a `enter code here`space
b c a
Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:
1
Enter name, colour and mass in kg separated by a `enter code here`space
c a b
Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:
3
Name: a Colour: b Weight: c
Name: b Colour: c Weight: a
Name: c Colour: a Weight: b
Enter option: (1) add fruit (2) quit (3) to print sorted by name (4) to print sorted by kg:
4
Name: b Colour: c Weight: a
Name: c Colour: a Weight: b
Name: a Colour: b Weight: c
于 2013-09-13T16:27:35.040 回答
0

尝试运行此代码。

import java.util.*;

/**
 * creates instances of the Fruits class, and stores the resulting objects in an
 * array which can be ordered firsting alphebetically by name, then by colour,
 * and finally, in ascending order by weight
*
 */
public class Driver {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int input = 0;

        ArrayList<Fruit> fruitInfo = new ArrayList<>();

        do {
            System.out.println("Enter option: (1) add fruit (2) quit:");
            input = s.nextInt();
            s.nextLine();

            switch (input) {
                case 1: {
                    System.out.println("Enter name, colour and mass in kg separated by a `enter code here`space");
                    String in = s.nextLine();
                    String[] temp = in.split(" ");

                    //create a new instance of the fruit class and add it to the `enter code here`<ArrayList> {@link ArrayList}, fruitInfo
                    fruitInfo.add(new Fruit(temp[0], temp[1], temp[2]));
                    Collections.sort(fruitInfo);
                    break;
                }

                case 2: {
                    break;
                }

                default:
                    System.out.println("Input incorrect. Try again.");
            }
        } while (input != 2);
    }
}

/* Class Fruits
 * a class modelled on the characteristics of fruit
 * each fruit has a name, colour and mass, which are
 * stored as <Strings>
 **/
class Fruit implements Comparable<Fruit> {

    private String name;
    private String col;
    private String kg;

    public int compareTo(Fruit otherFruit) {
        int nameCmp = name.compareTo(otherFruit.name);
        if (nameCmp != 0) {
            return nameCmp;
        }
        int colCmp = name.compareTo(otherFruit.col);
        if (colCmp != 0) {
            return colCmp;
        }
        return kg.compareTo(otherFruit.kg);
    }
    /* Constructor
     * constructs an instance of the Fruit class
     * using user defined characteristics
     **/

    public Fruit(String name, String colour, String mass) {
        this.name = name;
        col = colour;
        mass = kg;
    }
}
于 2013-09-13T16:15:31.600 回答