How to find length of a string array?

前端 未结 8 1191
温柔的废话
温柔的废话 2020-12-13 19:10

I am having a problem with the following lines where car is a String array which has not been initialized/has no elements.

String c         


        
8条回答
  •  情歌与酒
    2020-12-13 19:37

    Since car has not been initialized, it has no length, its value is null. However, the compiler won't even allow you to compile that code as is, throwing the following error: variable car might not have been initialized.

    You need to initialize it first, and then you can use .length:

    String car[] = new String[] { "BMW", "Bentley" };
    System.out.println(car.length);
    

    If you need to initialize an empty array, you can use the following:

    String car[] = new String[] { }; // or simply String car[] = { };
    System.out.println(car.length);
    

    If you need to initialize it with a specific size, in order to fill certain positions, you can use the following:

    String car[] = new String[3]; // initialize a String[] with length 3
    System.out.println(car.length); // 3
    car[0] = "BMW";
    System.out.println(car.length); // 3
    

    However, I'd recommend that you use a List instead, if you intend to add elements to it:

    List cars = new ArrayList();
    System.out.println(cars.size()); // 0
    cars.add("BMW");
    System.out.println(cars.size()); // 1
    

提交回复
热议问题