0

I'm having issues understanding ArrayList in Java. I tried to declare a Character ArrayList and add a char at 0, but it returned error at list.add(0, "B") line.

public class ArrListTest {
public static void main(String[] args) {
    ArrayList<Character> list;
    list.add(0, "B");
 }
}

Also I'm having issues reversing a string. Is there a way to reverse a string without using a loop?

user3807322
  • 5
  • 1
  • 1
  • 2

4 Answers4

3

"B" is instance of String, characters need to be surrounded with ' like 'B'.

use

list.add(0,'B');

If you want to add B after last element of list skip 0

list.add('B');

Also don't forget to actually initialize your list

List<Character> list = new ArrayList<>();
//                   ^^^^^^^^^^^^^^^^^^^

To know why I used List<Character> list as reference type instead of ArrayList<Character> list read:
What does it mean to “program to an interface”?

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
3

You're mixing up List.set with List.add. Use a character literal instead of a String and use

list.add('B');

after initializing the List

List<Character> list = new ArrayList<>();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

public class stackQuestions {

public static void main(String args[]) {

    ArrayList list = new ArrayList();

    list.add("b");
    list.add(0, "a");// it will add to index 0
    list.add(0, "c");// it will replaces to index 0
    System.out.println(list);
}

}

-1
public static void main(String args[]) {

    ArrayList list= new ArrayList();
        list.add("B");

}

try this

  • This only works for the first character you insert. The second one will not be placed at index 0. – BDL Jul 22 '19 at 08:15
  • list.add("b"); list.set(0, "a"); by this we can replace – KARTHIK SARAGADAM Jul 23 '19 at 09:24
  • op has to insert **a number of characters at index 0*. You approach (add) does only work for the first character you add to the list. Afterwards they are appended to the end and not at the beginning. – BDL Jul 23 '19 at 09:25