如何查找字符串数组的长度? [英] How to find length of a string array?

查看:142
本文介绍了如何查找字符串数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题,其中 car 是一个尚未初始化的 String 数组/没有元素。

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

String car [];
System.out.println(car.length);

什么是可能的解决方案?

What is a possible solution?

推荐答案

由于 car 尚未初始化,因此没有长度,其值为 null 。但是,编译器甚至不允许您编译代码,抛出以下错误:变量汽车可能尚未初始化

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.

您需要先进行初始化,然后才能使用 .length

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

但是,我建议你使用 List 相反,如果您打算向其添加元素:

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

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

这篇关于如何查找字符串数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆