Java String array: is there a size of method?

后端 未结 11 1985
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 03:38

I come from a php background and in php, there is an array_size() function which tells you how many elements in the array are used.

Is there a similar

相关标签:
11条回答
  • 2020-11-27 03:50

    Also, it's probably useful to note that if you have a multiple dimensional Array, you can get the respective dimension just by appending a '[0]' to the array you are querying until you arrive at the appropriate axis/tuple/dimension.

    This is probably better explained with the following code:

    public class Test {
        public static void main(String[] args){
            String[][] moo = new String[5][12];
    
            System.out.println(moo.length); //Prints the size of the First Dimension in the array
            System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
        }
    
    }
    

    Which produces the output:

    5
    12
    
    0 讨论(0)
  • Yes, .length (property-like, not a method):

    String[] array = new String[10];
    int size = array.length;
    
    0 讨论(0)
  • 2020-11-27 03:59
    array.length
    

    It is actually a final member of the array, not a method.

    0 讨论(0)
  • 2020-11-27 03:59

    array.length final property

    it is public and final property. It is final because arrays in Java are immutable by size (but mutable by element's value)

    0 讨论(0)
  • 2020-11-27 04:03

    All the above answers are proper. The important thing to observe is arrays have length attribute but not length method. Whenever you use strings and arrays in java the three basic models you might face are:

    1. String s=new String("vidyasagar");
      System.out.println(s.length()); // In this case we are using only String. No length attribute for Strings. we have to use length() method.
    2. int[] s=new int[10]; System.out.println(s.length); //here we use length attribute of arrays.
    3. String[] s=new String[10];
      System.out.println(s.length); // Here even though data type is String, it's not a single String. s is a reference for array of Strings. So we use length attribute of arrays to express how many strings can fit in that array.
    0 讨论(0)
  • 2020-11-27 04:09

    In java there is a length field that you can use on any array to find out it's size:

        String[] s = new String[10];
        System.out.println(s.length);
    
    0 讨论(0)
提交回复
热议问题