gpt4 book ai didi

java - 将迭代器添加到我的数组列表中

转载 作者:行者123 更新时间:2023-11-30 03:28:03 25 4
gpt4 key购买 nike

import java.util.Iterator;

public class MyArrayList<E> implements Iterable<E> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;

public MyArrayList() {
size = 0;
capacity = DEFAULT_SIZE;
items = new Object[DEFAULT_SIZE];
}

private void expand() {
Object[] newItems = new Object[capacity + EXPANSION];
for (int j = 0; j < size; j++) newItems[j] = items[j];
items = newItems;
capacity = capacity + EXPANSION;
}

public void add(Object obj) {
if (size >= capacity) this.expand();
items[size] = obj;
size++;
}

public int size() {
return size;
}

public Object get(int index) {
try{
return items[index];
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}

public boolean contains(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return true;
}
return false;
}

public void add(int index, Object obj) {
try{
if (size >= capacity) this.expand();
for (int j = size; j > index; j--) items[j] = items[j - 1];
items[index] = obj;
size++;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}

public int indexOf(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return j;
}
return -1;
}

public boolean remove(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) {
for (int k = j; k < size-1; k++) items[k] = items[k + 1];
size--;
items[size] = null;
return true;
}
}
return false;
}

public Object remove(int index) {
try{
Object result = this.get(index);
for (int k = index; k < size-1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return result;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}

public void set(int index, Object obj) {
try{
items[index] = obj;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}




public Iterator<E> iterator() {

return new MyIterator<E>();
}

public class MyIterator <T> implements Iterator<T>{
public boolean hasNext(){

}

public T next(){

}

public void remove(){

}
}


}

基本上,我正在尝试改进数组列表的功能,因为它使用 for 循环来执行添加和删除等方法,但是我正在尝试使用迭代器,我搜索了它,发现你不能只是只需在主类中添加实现iterable即可,它必须使用三个方法next()、hasNext()和remove()来实现。我在代码底部添加了这三个方法,但我真的不确定如何实现它才能使其开始工作。

最佳答案

您需要跟踪 items 中的索引数组 Iterator已开启。我们称之为int currentIndexhasNext()将返回true如果currentIndex < sizenext()将增加currentIndex如果hasNext()true并返回items[currentIndex] ,否则它应该抛出 Exception ,比如说NoSuchElementException 。删除会调用remove(currentIndex) .

关于java - 将迭代器添加到我的数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699188/

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