Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting arraylist int to string

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;
}
like image 316
Dick Avatar asked May 24 '15 07:05

Dick


People also ask

Can I convert int to String?

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.

Can Integer array convert to ArrayList?

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.


1 Answers

  • Your loop had the wrong range and it didn't do anything, since you terminated it with ;.
  • In addition, 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();
    
like image 188
Eran Avatar answered Sep 22 '22 23:09

Eran