将某个大小初始化为数组

时间:2021-02-17 18:40:33

Hi i'm trying to create an array with a prefixed size(eg,size of 10) in the Main and then add items(eg, 3 items) in the array, this will make the array have 7 unused spaces, later on, I want to write a method that trim the unused size.

嗨我正在尝试在Main中创建一个带有前缀大小(例如,大小为10)的数组,然后在数组中添加项目(例如,3个项目),这将使该数组有7个未使用的空间,稍后,我想写一个修剪未使用大小的方法。

But How can i first create an array with a fixed size because obviously my constructor won't allow this operation below.

但是我怎么能首先创建一个固定大小的数组,因为很明显我的构造函数不允许在下面进行这个操作。

*Bag<String> names = new Bag<String>(**10**);*


public class Bag<T extends Comparable<T>> implements Iterable<T> {
  private int MAX_ITEMS = 10; // initial array size
  private int size;
  private T[] data;

  public Bag( ) {
      data = (T []) new Comparable[MAX_ITEMS];
      size = 0;
      }

  public static void main(String[ ] args) {
      Bag<String> names = new Bag<String>();
        names.add("Seattle");
        names.add("Chicago");
        names.add("New York");

        System.out.println(names.size());
        for (String name : names)
            System.out.println(name);

        names.trimToSize();
        System.out.println(names.size());
  }
}

1 个解决方案

#1


You can create the following method in a Utility class and use it every time you need it:

您可以在Utility类中创建以下方法,并在每次需要时使用它:

public static <T> T[] newArrayOf(T[] t, int len){
        return (T[]) Array.newInstance(t.getClass().getComponentType(), len);
    }

#1


You can create the following method in a Utility class and use it every time you need it:

您可以在Utility类中创建以下方法,并在每次需要时使用它:

public static <T> T[] newArrayOf(T[] t, int len){
        return (T[]) Array.newInstance(t.getClass().getComponentType(), len);
    }