Reputation: 43579
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.
Upvotes: 4
Views: 69373
Reputation: 1109342
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<>();
// ...
Upvotes: 19
Reputation: 533730
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[].
Upvotes: 4
Reputation: 9648
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.
Upvotes: 0
Reputation: 19340
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.)
Upvotes: 1
Reputation: 597314
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>
Upvotes: 6
Reputation: 7070
You cannot create an array without a length only with a length of 0, and why would u want that?
Upvotes: 2
Reputation: 272677
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.
Upvotes: 1