Shamoon
Shamoon

Reputation: 43579

How can I create a character array in Java without a specified length?

    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

Answers (9)

BalusC
BalusC

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<>();
// ...

See also:

Upvotes: 19

Mouad Debbar
Mouad Debbar

Reputation: 3236

you should use:

char[] ret = {};

Upvotes: 3

Peter Lawrey
Peter Lawrey

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

Roy T.
Roy T.

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

Andrew Lazarus
Andrew Lazarus

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

Bozho
Bozho

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

SLaks
SLaks

Reputation: 887867

You're probably looking for an ArrayList<Character>.

Upvotes: 14

RMT
RMT

Reputation: 7070

You cannot create an array without a length only with a length of 0, and why would u want that?

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions