hi i'm trying create array prefixed size(eg,size of 10) in main , add items(eg, 3 items) in array, make array have 7 unused spaces, later on, want write method trim unused size.
but how can first create array fixed size because constructor won't allow 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()); (string name : names) system.out.println(name); names.trimtosize(); system.out.println(names.size()); } }
you can create following method in utility class , use every time need it:
public static <t> t[] newarrayof(t[] t, int len){ return (t[]) array.newinstance(t.getclass().getcomponenttype(), len); }
Comments
Post a Comment