我有一种方法可以将通用元素的集合添加到数组中,但是不知道如何实现。我已将遇到问题的代码行标记为COLLECTION
。我不知道该怎么写。我的数组是一个圆环数组。
import java.util.Collection;
import java.util.Iterator;
public class CircularArrayRing<E> implements Ring<E> {
public E[] elements; //array of E
private int capacity;
private int writePos = 0;
private int available = 0;
public CircularArrayRing(int size) { //circular array constructor
capacity = size;
}
public boolean add(E e) {
if(available < capacity){
if(writePos >= capacity){
writePos = 0;
}
elements[writePos] = e; //add element e
writePos++;
available--;
return true;
}
return false;
}
public boolean addAll(Collection<? extends E> c) {
if(available < capacity){
if(writePos >= capacity){
writePos = 0;
}
elements[writePos] = COLLECTION; //how do add a collection of elements?
writePos++;
available++;
return true;
}
return false;
}
}
最佳答案
一次迭代和触发add()
怎么样?
public boolean addAll(Collection<? extends E> c){
for(E e : c){
add(e);
}
}