سؤال

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>();
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

its Character not char

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

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

Try Character,

ArrayList<Character> characterList = new ArrayList<Character>();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top