Java 选择arraylist中的元素并交换到下一个元素和上一个元素

Java 选择arraylist中的元素并交换到下一个元素和上一个元素,java,arraylist,swap,Java,Arraylist,Swap,我的疑问是如何在ArrayList中选择一个元素,以便在需要向下移动该元素并切换到上一个元素的情况下可以与下一个元素交换。在这种情况下,请向上移动该项 public class ShapesFX{ private ArrayList <Shape> shapes; public ShapesFX() { this.shapes= new ArrayList <> (); } / ** *

我的疑问是如何在ArrayList中选择一个元素,以便在需要向下移动该元素并切换到上一个元素的情况下可以与下一个元素交换。在这种情况下,请向上移动该项

public class ShapesFX{

        private ArrayList <Shape> shapes;

        public ShapesFX() {
            this.shapes= new ArrayList <> ();
    }

  / **
     * Swap positions with the immediate previous element. The method can not
     * Be successful if the reference element is the last.
     *
     * @ Param element element reference to the exchange
     * @ Return true if the exchange was successful. false, d.c.
     * @ Throws Exception if the element does not exist
     * /

    @ Override
    public boolean moveUP (Shape element) throws Exception {
        if (element != null) {
            throw new Exception ("Element does not exist");
        } else if (element != Null) {
            for (FormaGeometrica sh : this.shapes) {
                if (sh == element) {
                    Collections.swap ((List<Shape>) element, 0, 0);
                }
            }
            return true;
        }
        return false;
    }

  / **
     * Swap positions with the next immediate element. The method can not
     * Be successful if the reference element is the first.
     *
     * @ Param element element reference to the exchange
     * @ Return true if the exchange was successful. false, d.c.
     * @ Throws Exception if the element does not exist
     * /

    @ Override 
    public boolean moverDown (Shape element) throws Exception {
        if (element != null) {
            throw new Exception ("Element does not exist");
        } else if (element != Null) {
            for (Shape sh : this.shapes) {
                if (sh == element) {
                    Collections.swap ((List<Shape>) element, 0, 0);
                }
            }
            return true;
        }
        return false;
    }

可能重复:选择要移动的元素的索引,并与上一个索引元素或下一个索引中的元素交换。是否可以确保发布的代码使用java编译器编译?示例:Else->Else,!=->!=,/***->/**等等。我认为您需要重新阅读Collections.swap的Javadoc。您正在将形状强制转换为列表,并且为两个索引参数指定了相同的值。谢谢@Erwin Bolwidt,这是我的错,但我现在重新编辑了代码
--- List of Figures ---
F1
F2
F3
F4

--- Move F2 UP ---
F2
F1
F3
F4

F2 change position with F1

--- Move F3 DOWN ---
F2
F1
F4
F3

F3 change position with F4