Dick
Dick

Reputation: 53

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;
}

Upvotes: 5

Views: 12279

Answers (4)

quiZ___
quiZ___

Reputation: 119

A ListIterator works too - if you dont want indexing.

ArrayList<Integer> integerList = new ArrayList<Integer>();
StringBuilder sb = new StringBuilder();
ListIterator<Integer> it = integerList.listIterator(integerList.size());


while(it.hasPrevious())
{
    sb.append(Integer.toString(it.previous()));
}

String answer = sb.toString();

Upvotes: 0

Alaa Abuzaghleh
Alaa Abuzaghleh

Reputation: 1009

public String toString() {
        int n = arrList.size();
        if (n == 0)
            return "0";

        String str = "" ; 
        for (int i = arrList.size()-1; i > 0; i--){
        int nums= arrList.get(i);
        str+= nums ; 
        }


        return str;
}

Upvotes: 0

Maroun
Maroun

Reputation: 95968

You have many problems. First, you should remove ; after the for loop.

Second, you are not concatenating the result, just saving the last value.

Third, you should loop from the last index, which is arrList.size() - 1.

Fourth, note that the element at place 0 should be counted as well, so you should change your condition to i >= 0.

Finally, accessing arraylist's elements should be done using the method get: arrList.get(i).

Now after you understood what your problems are, I would like to suggest a better solution using Java 8:

Collections.reverse(arrList);
String listString = arrList.stream().map(Object::toString)
                    .collect(Collectors.joining(""));

Upvotes: 1

Eran
Eran

Reputation: 393831

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

Upvotes: 6

Related Questions