gpt4 book ai didi

java - 如何从数组末尾删除一个元素并将其插入到前面

转载 作者:行者123 更新时间:2023-11-29 09:31:39 25 4
gpt4 key购买 nike

我正在使用 arraylist 工具。我想编写一个获取最后一个元素并将其插入到前面的方法。到目前为止,我得到了最后一个元素并将其插入前面,然后将所有内容都移了过来。但是,我似乎无法删除前面插入的最后一个元素。例如:(1,2,5)到(5,1,2)但我得到了(5,1,2,5)。我在我的 replaceArray() 方法中遗漏了一些东西,但我真的不知道是什么。感谢您的帮助。

类的构造函数:

public KWArrayList() {
capacity = INITIAL_CAPACITY;
theData = (E[]) new Object[capacity];
}

public void replaceArray(int index, E anElement) {
for (int i = size; i > index; i--){
theData[i] = theData[i - 1];
}

theData[index] = anEntry;

size--;

for (int i = 0; i < theData.length; i++){
System.out.println(theData[i]);
}
}

最佳答案

我会使用这种旋转数组的简单方法(我认为该方法应该称为 rotate 而不是 replaceAll,因为它实际上是将数组旋转一个位置) .

这是方法 rotate():

@SuppressWarnings("unchecked")
public void rotate() {
Object[] temp = new Object[theData.length];
//copy each element, except the first, from theData into temp by shifting one position off to the right
for (int i = temp.length - 1; i > 0; i--) {
temp[i] = theData[i - 1];
}
//move the last element into the first position
temp[0] = theData[theData.length - 1];
//update theData
theData = (T[]) temp;
}

完整的可测试示例

public class MyArrayList<T> {
int INITIAL_CAPACITY = 10;
int capacity;
T[] theData;

@SuppressWarnings("unchecked")
public MyArrayList() {
capacity = INITIAL_CAPACITY;
theData = (T[]) new Object[capacity];
}

@SuppressWarnings("unchecked")
public MyArrayList(int capacity) {
this.capacity = capacity;
theData = (T[]) new Object[this.capacity];
}

@SuppressWarnings("unchecked")
public void rotate() {
Object[] temp = new Object[theData.length];
//copy each element, except the first, from theData into temp by shifting one position off to the right
// to the right
for (int i = temp.length - 1; i > 0; i--) {
temp[i] = theData[i - 1];
}
// move the last element into the first position
temp[0] = theData[theData.length - 1];
// update theData
theData = (T[]) temp;
}

/**
* For testing purposes only. It doesn't handle out of bounds values of
* index.
*/
private void insert(T t, int index) {
theData[index] = t;
}

public void print() {
for (T t : theData) {
System.out.print(t + ", ");
}
System.out.println();
}

@SafeVarargs
public static <E> MyArrayList<E> of(E... elements) {
MyArrayList<E> m = new MyArrayList<>(elements.length);
for (int i = 0; i < elements.length; i++) {
m.insert(elements[i], i);
}
return m;
}
}

测试rotate()方法:

public class TestMyArrayList {
public static void main(String[] args) {
MyArrayList<Integer> m = MyArrayList.of(1, 2, 3, 4, 5);
m.print();
m.rotate();
m.print();
}
}

它会打印出:

1, 2, 3, 4, 5, 
5, 1, 2, 3, 4,

关于java - 如何从数组末尾删除一个元素并将其插入到前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48590656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com