I am trying to convert an arraylist of integers to an string in reverse. eg (1,2,3,4) converts to "4321".
However I am unable to get my code to work mainly due to the primitive data type error (basically why you give my an arraylist to do an array thing). My code is currently
public String toString() {
int n = arrList.size();
if (n == 0)
return "0";
for (int i = arrList.size(); i > 0; i--);
int nums= arrList[i];
char myChar = (char) (nums+ (int) '0');
String result = myChar.toString(arrList);
return result;
}
We can convert int to String in java using String.valueOf() and Integer.toString() methods. Alternatively, we can use String.format() method, string concatenation operator etc.
An array can be converted to an ArrayList using the following methods: Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.
;
. arrList[i]
is the way to access an element of an array. To access an element of an ArrayList you use arrList.get(i)
. Finally, you should accumulate the characters / digits somewhere before converting them to a String. I suggest a StringBuilder.
StringBuilder sb = new StringBuilder();
for (int i = arrList.size() - 1; i >= 0; i--) {
int num = arrList.get(i);
sb.append(num);
}
String result = sb.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With