【问题标题】:How to create a collection constructor that gets array into new array如何创建将数组放入新数组的集合构造函数
【发布时间】:2013-10-06 20:06:39
【问题描述】:

我需要一个创建集合构造函数。 这是一个构造函数将它的所有元素从我的数组复制到新的 TimeArrayList 中。

到目前为止,我的构造函数看起来像这样

private E[] timeData;
private int capacity = 0;

public TimeArrayList(Collection<? extends E> c) {
    timeData = (E[]) new Object[capacity];
    for (int i = 0; i < timeData.length; i++) {
  //this is where  im having the problem
}
}

我不知道如何从我的数组中获取值并创建一个数组列表。我想我还必须在某个地方放置一个迭代器。

【问题讨论】:

  • 您会注意到 Collection 扩展了 Iterable。此外,您当前正在创建一个大小为 0 的数组。
  • 数据是在我这样做之后添加的。
  • 添加了什么?您的数组大小为 0。
  • 您的阵列容量为零?在这种情况下,您必须使用:timeData = (E[]) new Object[c.size()];,然后:for (int i = 0; i
  • 为什么不直接调用 Collection 的 toArray 方法呢? docs.oracle.com/javase/7/docs/api/java/util/…

标签: java arrays collections arraylist constructor


【解决方案1】:

我要做的是检查 C 中元素的数量,并使用迭代器来迭代这些元素并将它们添加到您的 timeData 数组中。

另外,正如 arynaq 所说,你也可以使用 toArray() 方法:见https://stackoverflow.com/a/3293970/1688441

public TimeArrayList(Collection<? extends E> c) {

        //Long way
        timeData = (E[]) new Object[c.size()];
        int element = 0;

        Iterator<? extends E> it = c.iterator();
        while(it.hasNext())timeData[element++] = it.next();

        //Short way
        timeData = c.toArray(timeData);     

    }

【讨论】:

    【解决方案2】:

    获取类型数组的最简单方法 首先,您需要为数据分配空间:

    timeData = new (E[]) new Object[c.size()];
    

    之后可以添加c的内容,例如:

    编辑:更改为使用 cmets 中指出的 toArray。

    c.toArray(timeData);
    

    但实际上,最简单的方法是利用标准库而忘记手动使用数组:

    List<E> timeData;
    ...
    // and in constructor:
    timeData = new ArrayList<E>(c);
    

    【讨论】:

    • 更快/更容易使用:timeData = c.toArray(timeData);
    • @meewoK 是的,我忘记了那个方法。我将编辑答案(我猜 OP 对 ArrayList 感兴趣。
    【解决方案3】:

    如果没有capacity,我会这样写:

     public class TimeArrayList<E> {
    
       private List<? super E>  timeData = null;
    
       public TimeArrayList(Collection<? extends E> src) {
    
         this.timeData = new ArrayList<E>(src.size());
    
         Iterator<? extends E> collectionIterator = src.iterator();
    
         for (int i = 0; collectionIterator.hasNext(); i++) {
             this.timeData.set(i, collectionIterator.next());
         }  
       }
    }
    

    疑问句? super E 表示目标列表可能包含任何类型的元素 这是E 的超类型,就像源列表可能包含任何类型的元素一样 E 的子类型。

    【讨论】:

    • @RiseLC 如果您用作源 Collection 我认为目标也应该是 Collection(如 List)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多