Java dynamic array sizes?

前端 未结 18 2164
星月不相逢
星月不相逢 2020-11-22 04:37

I have a class - xClass, that I want to load into an array of xClass so I the declaration:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
my         


        
18条回答
  •  别那么骄傲
    2020-11-22 05:30

    In java array length is fixed.

    You can use a List to hold the values and invoke the toArray method if needed See the following sample:

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Random;
    
    public class A  {
    
        public static void main( String [] args ) {
            // dynamically hold the instances
            List list = new ArrayList();
    
            // fill it with a random number between 0 and 100
            int elements = new Random().nextInt(100);  
            for( int i = 0 ; i < elements ; i++ ) {
                list.add( new xClass() );
            }
    
            // convert it to array
            xClass [] array = list.toArray( new xClass[ list.size() ] );
    
    
            System.out.println( "size of array = " + array.length );
        }
    }
    class xClass {}
    

提交回复
热议问题