Reputation: 5
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?
Upvotes: 0
Views: 18987
Reputation: 1
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);
}
}
Upvotes: 0
Reputation: 1
public static void main(String args[]) {
ArrayList list= new ArrayList();
list.add("B");
}
try this
Upvotes: -1
Reputation: 159754
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<>();
Upvotes: 3
Reputation: 124215
"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”?
Upvotes: 3