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

5
我尝试使用 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
            }
        }

5
我的第一印象是由于您的CreateShape类没有扩展Comparable接口。您需要重写compare()方法来使排序正常工作。 - CubeJockey
请查看此链接:http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/ 您需要在Shape类中实现Comparable和Comparator,然后可以在您的ArrayList上使用Collections.sort()。 - Jonas Czech
您可以通过覆盖 compare() 方法来扩展 Comparator()。 - BufBills
2
目前你有CreateSpace实现了Space,你需要改为CreateSpace实现了Space和Comparable<Space> - Transcendence
可能是Sort Java Collection的重复问题。 - ericbn
1个回答

2
您遇到了这个错误,是因为当您调用Collections.sort()并仅传递一个List<T>作为参数时,它期望列表元素实现Comparable接口。由于CreateShape没有实现该接口,sort()无法知道如何对这些对象进行排序。
以下是两个您应该考虑的选项:
  1. CreateShape could implement Comparable<CreateShape>: do this if you think CreateShape instances have a natural order in which they should be sorted. If you wanted to sort by a char field, for example:

    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. Create a custom Comparator<CreateShape>: do this if you want to sort CreateShape instances arbitrarily. You could have a Comparator that sorts by name, another that sorts by id, etc. Example:

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

谢谢回复,@AndersonVieira!但是我正在尝试比较char displayChar(因为我没有任何字符串值),但是当我执行此操作时出现错误:return this.dc.compareTo(other.dc); - user4833678
@John 如果你想比较 chars,你可以这样做 return Character.compare(c1, c2);。我已经更新了答案。 - Anderson Vieira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接