【问题标题】:Sorting an ArrayList according to 3 customised Strings in Java根据 Java 中的 3 个自定义字符串对 ArrayList 进行排序
【发布时间】:2013-09-13 15:57:48
【问题描述】:

我正在尝试使用 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;
} 
}

【问题讨论】:

标签: java sorting arraylist customization


【解决方案1】:

让你的 Fruit 类实现 Comparable 并在

中实现你的比较逻辑
public class Fruit implements Comparable<Fruit>
...

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

}

然后您可以使用 Collections.sort(myList); 对列表进行排序

【讨论】:

    【解决方案2】:

    你应该实现一个比较器

    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());
    

    【讨论】:

      【解决方案3】:

      尝试运行这段代码。

      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;
          }
      }
      

      【讨论】:

        【解决方案4】:

        如果你的 Fruit 类实现了 java Comparator 接口(在 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-22
          • 2011-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-20
          • 1970-01-01
          • 2015-11-30
          相关资源
          最近更新 更多