我尝试使用 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()
无法知道应该如何对这些对象进行排序。
以下是您应该考虑的两个选项:
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);
创建自定义
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/