1

Why can't I declare an ArrayList of char, I know the String class exist but it still seem weird I can't do the following piece of code

ArrayList<char> foo = new ArrayList<char>();
1
  • 3
    You need to use the reference type: Character. Commented Apr 1, 2014 at 16:05

4 Answers 4

4

You cannot use primitive types as a generic type-parameter; you need to use the wrapper class for char, which is Character:

List<Character> characterList = new ArrayList<>(); //Java 7

or

List<Character> characterList = new ArrayList<Character>(); //Java 5,6

This goes for any class that accepts a generic type-parameter. So for example, if you had tried to use int, you would get the same error. Instead, you would have had to use Integer.

Sign up to request clarification or add additional context in comments.

Comments

3

Collections do not allow the use of primitive types. You'd encounter this error had you tried any of the primitives, (int, long, double, etc..). Use a primitive wrapper such as Character, to declare the collection.

ArrayList<Character> foo = new ArrayList<Character>();

Comments

3

its Character not char

List<Character> foo = new ArrayList<Character>();

From starting letter you can easily makeout that char is not class

2 Comments

Not sure, mine got down voted to.. I'm wondering if someone is trying to boost their answer?
@PatrickJAbareII I think so. My answer was downvoted as well. I've upvoted your answers.
1

Try Character,

ArrayList<Character> characterList = new ArrayList<Character>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.