char ret[] = {};
Doesn't work seem to work and I'm not sure what the best way to do this is开发者_运维问答.
Any help would be greatly appreciated.
Arrays must have a fixed length.
If your goal is to have a dynamically expansible list, consider a List
instead. Everytime you add an item by add()
method, it will grow dynamically whenever needed.
List<Character> chars = new ArrayList<Character>();
// ...
See also:
- Java Tutorials - Trail: Collections - The List Interface
You're probably looking for an ArrayList<Character>
.
char[] ret = new char[0];
this will create an empty array. But you can use it only as a placeholder for cases when you don't have an array to pass.
If you don't know the size initially, but want to add to the array, then use an ArrayList<Character>
The best way to have an extensible array of char without the overhead of an Character object for each char, is to use a StringBuilder. This allows you to build an array of char in a wide variety of ways. Once you are finished you can use getChars() to extract a copy of the char[].
you should use:
char[] ret = {};
You cannot create an array without a length only with a length of 0, and why would u want that?
Your question doesn't really make sense; an array always has some length. But is this what you were thinking of?
char[] ret = null;
This creates a reference to an array, but initialises it to null
. There is no actual array yet.
Methinks you are still thinking in C or Pascal. The functionality you want is probably a Java String. char[]
is uncommon in Java. (You can iterate through the chars of a string with charAt
, among other possibilities.)
You probably come from PHP or another programming language that hasn't got real arrays. (An array in PHP is a sort of dictionary/hashmap)
Arrays in JAVA are fixed length.
For no fixed length, you can use a Vector. If you want to index with something else than integers from 0 to length, you can use a Dictionary.
精彩评论