简体   繁体   中英

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

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(""));
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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM