如何将元素集合添加到我的数组?

时间:2016-03-07 17:15:49

标签: java arrays collections

我有一种方法可以将一组通用元素添加到我的数组中,但不知道如何实现它。我已经将我遇到的代码行标记为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;
    }
}

4 个答案:

答案 0 :(得分:3)

如何逐个迭代和触发add()

public boolean addAll(Collection<? extends E> c){
  for(E e : c){
    add(e);
  }
}

答案 1 :(得分:1)

功能方式。

c.forEach(this::add);

答案 2 :(得分:0)

你可以在这里找到一些想法:

https://github.com/bekkopen/Continuous-Delivery-example/blob/master/webapp/src/main/java/no/bekk/bekkopen/cde/jetty/config/CollectionBuilder.java#L10

public static <T> Set<T> newSet(final T... elements) {
    return new HashSet<T>(Arrays.asList(elements));
}

public static <T> List<T> newList(final T... elements) {
    return new ArrayList<T>(Arrays.asList(elements));
}

答案 3 :(得分:0)

以下是一些例子:

String.Format("<p class=""MsoNormal""><span style='color:#1F497D'> {0} has added {1} to the database</span></p>", NameOfPerson.Value, AmountOfNewEntries.Value)

完整代码:

http://code.openhub.net/file?fid=WKY7Buaz9RI_B0BqM_HKnkm6lqY&cid=9RkvURzZ1wM&s=How%20to%20Add%20a%20collection%20of%20elements%20to%20my%20array%3F&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&filterChecked=true&mp=1&ml=1&me=1&md=1#L79