简体   繁体   English

如果大小未知,如何在 java 中使用 char 数组?

[英]How to use a char array in java if the size is unknown?

If I don't know the size of array of chars I'm using, is there a way to use it without setting the size upfront?如果我不知道我正在使用的字符数组的大小,有没有办法在不预先设置大小的情况下使用它?

In general, you can use a java.util.List when you don't know the size up front.通常,当您不知道前面的大小时,可以使用java.util.List

List<Character> chars = new ArrayList<Character>();
chars.add('f');
chars.add('o');
chars.add('o');

Depending on your needs, a StringBuilder might make more sense than a List<Character> .根据您的需要, StringBuilder可能比List<Character>更有意义。

StringBuilder sb = new StringBuilder();
sb.append('f')
  .append('o')
  .append('o');

If you want to get really slick, use Trove for its list-of-primitives so you can work with the (third-party equivalent of) a List<char> .如果您想变得非常漂亮,请使用Trove作为其原始列表,以便您可以使用List<char>的(第三方等价物)。 nevermind.没关系。 Trove does not have a TCharArrayList . Trove没有TCharArrayList

Can you use a String or a StringBuilder and then convert it to a char array later?您可以使用 String 或 StringBuilder 稍后将其转换为 char 数组吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM