Мой код:Что случилось с HashMap?
Это GUI программа
Обращаю некоторый прямоугольник, и поместить их в HashMap формы (используйте addShape()); currShape
указывает на форму, удерживаемую мышью. Когда мышь нажимает (mousePressed()) Я хочу изменить элемент, но я не могу его найти, хотя hashCode() и equal() совпадают.
HashMap<Shape, ShapeInfo> shapes;
private Shape currShape = null;
public void addShape(Point point)
{
switch (actState)
{
case DRAWREC:
currShape = new Rectangle(point);
break;
case DRAWCIR:
currShape = new Ellipse2D.Double(point.getX(), point.getY(), 10.0, 10.0);
break;
case DRAWLIN:
currShape = new Line2D.Double(point.getX(), point.getY(), point.getX(), point.getY());
break;
default:
break;
}
shapes.put(currShape, new ShapeInfo(false, color));
repaint();
}
public Shape findShape(Point point)
{
int curx = point.x, cury = point.y;
for (Shape shape : shapes.keySet())
{
if (shape instanceof Rectangle)
{
Rectangle rec = (Rectangle)shape;
if (!drawCompleted(rec) && (rec.contains(point) ||
rec.contains(curx, cury - ShapeInfo.SIZE) || rec.contains(curx, cury + ShapeInfo.SIZE) ||
rec.contains(curx - ShapeInfo.SIZE, cury) || rec.contains(curx + ShapeInfo.SIZE, cury)))
return shape;
}
}
return null;
}
public void mousePressed(MouseEvent event)
{
Shape shape = findShape(event.getPoint());
System.out.println(shape);
if (currShape != null && currShape != shape)
setComplted();
currShape = shape;
if (event.getButton() == MouseEvent.BUTTON1 &&
currShape == null || drawCompleted(currShape))
addShape(event.getPoint());
posState = getPos(event.getPoint());
}
public void setComplted()
{
try
{
System.out.println("Completed");
System.out.println(shapes.size());
for (Shape shape : shapes.keySet())
{
if (shape.equals(currShape))
System.out.println("equal : " + shape + ":" + shape.hashCode());
else
System.out.println(shape + ":" + shape.hashCode());
}
System.out.println("Current" + ":" + currShape + ":" + currShape.hashCode());
System.out.println(shapes.containsKey(currShape) + "\n");
}
catch (Exception error)
{
error.printStackTrace();
}
}
В результате
equal
java.awt.Rectangle[x=199,y=37,width=176,height=194]:776675328
java.awt.Rectangle[x=199,y=37,width=176,height=194]:776675328
false
The hashCode()
одинаковы и equals()
возвращение верно, но почему containKey
возвращение ложным? Почему он не может найти currShape
в формах?
Вы используете стандартные реализации классов HashMap и Shape? Код работает для меня –
Можете ли вы предоставить код, в котором определяется 'shape'. Кроме того, что такое класс, используемый 'currShape' и помещенный в' shape' ?? –
Вы переопределили 'equal' в форме? – user902383