简体   繁体   中英

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.

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 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> . nevermind. Trove does not have a TCharArrayList .

Can you use a String or a StringBuilder and then convert it to a char array later?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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