java - 使用 Collections.sort() 方法按字母顺序对对象进行排序

标签 java

我尝试使用 Collections.sort(shapes) 但它给了我这个错误:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the 
 arguments (ArrayList<CreateShape>). The inferred type CreateShape is not a valid substitute for the 
 bounded parameter <T extends Comparable<? super T>>

我该如何解决?

创建空间类

 public class CreateSpace implements Space{

            private int height;
        private int width;
        private String layout;
        private char[][] space;
        private Shape originalShape;
        private ArrayList<CreateShape> shapes = new ArrayList<CreateShape>();

        public CreateSpace(int height, int width, char[][] space, String layout)
        {
            this.height = height;
            this.width = width;
            this.space = space;
            this.layout = layout;
        }
    public void placeShapeAt(int row, int col, Shape shape)
        {

            int sHeight = shape.getHeight();
            int sWidth = shape.getWidth();
            if(shape.getHeight() + row > space.length || shape.getWidth() + col > space[0].length)
                throw new FitItException("Out of bounds!");
            char [][] spaceWithShapes = space;
            if(shapeFitsAt(row, col, shape) == true)
            {
                for(int r = 0; r < sHeight; r++)
                {
                    for(int c = 0; c < sWidth; c++)
                    {

                        if(spaceWithShapes[r+row][c+col] == '.' && shape.isFilledAt(r, c) == false)
                            spaceWithShapes[r+row][c+col] = (((CreateShape)shape).getShape()[r][c]);
                    }
                //  shapes.add((CreateShape)shape);
                    Collections.sort(shapes); // <<------- getting an error here
                }
                spaceWithShapes = space;
                shapes.add((CreateShape)shape);
Collections.sort(shapes); // <<------- getting an error here
            }
        }

最佳答案

你得到这个错误是因为当你调用 Collections.sort()仅传递 List<T>作为参数,它期望列表元素实现 Comparable界面。因为这不是 CreateShape 的情况。 , sort()无法知道应该如何对这些对象进行排序。

以下是您应该考虑的两个选项:

  1. CreateShape可以实现 Comparable<CreateShape> :如果您认为 CreateShape,请执行此操作实例有一个自然的顺序,它们应该被排序。如果你想按 char 排序字段,例如:

    class CreateShape implements Comparable<CreateShape> {
         private char displayChar;
    
         public char getDisplayChar() {
             return displayChar; 
         }
    
         @Override
         public int compareTo(CreateShape that) {
             return Character.compare(this.displayChar, that.displayChar);
         }
     }
    

然后你可以简单地调用Collections.sort() :

Collections.sort(shapes);
  1. 创建自定义 Comparator<CreateShape> : 如果你想对 CreateShape 进行排序,请执行此操作任意实例。你可以有一个 Comparator一个按名称排序,另一个按 id 排序,等等。示例:

    enum DisplayCharComparator implements Comparator<CreateShape> {
        INSTANCE;
    
        @Override
        public int compare(CreateShape s1, CreateShape s2) {
            return Character.compare(s1.getDisplayChar(), s2.getDisplayChar());
        }
    }
    

然后你应该调用Collections.sort()将比较器作为参数传递:

Collections.sort(shapes, DisplayCharComparator.INSTANCE);

注意我实现了DisplayCharComparator作为单例。那是因为它没有状态,所以没有必要拥有这个比较器的多个实例。另一种方法是使用静态变量:

class CreateShape {

    static final Comparator<CreateShape> DISPLAY_CHAR_COMPARATOR =
        new DisplayCharComparator();

    static class DisplayCharComparator implements Comparator<CreateShape> { ... }

    // rest of the code
}

或者,如果您使用的是 Java 8,则可以使用 Comparator.comparing :

shapes.sort(Comparator.comparing(CreateShape::getDisplayChar));

关于java - 使用 Collections.sort() 方法按字母顺序对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29905383/

相关文章:

java - 从环境变量构建数据库连接字符串

java - 如何在java中检查元素中的字符串是否为 "valid date formate"、 "today"或 "yesterday"

java - for 循环制作跳房子结构?

java - 如何使用 selenium webdriver 和 Java 从 kendo 下拉列表中选择一个选项

java - 递归函数来区分数组中的两个值

java - Android Firebase 。将数据添加到特定用户 Firebase 数据库

java - 是否可以将这两行写为三元运算符?

java - 如何打开 weblogic 的调试和跟踪日志记录?

java - 发送前编辑 HTML 响应

java - rxJava 等待特定值序列的更好方法