-1

I have this class has constructor taking a String and a Arraylist as argument;

class Foo{
    String ide;
    ArrayList list;

    public TypeOperator(String ide, ArrayList list){
        this.ide = ide;
        this.list = list;
    }
}

so when I initialise the class like below:

ArrayList<SomeType> list = new ArrayList<Some Type>;
list.add(SomeType1);
list.add(SomeType2);
Foo one = new Foo("->", list);

is there a way to print the format like below:

SomeType 2 -> SomeType 1

Let's say I have a SomeType class. Do I have something to do in the SomeType class?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Anda Zhao
  • 51
  • 1
  • 9
  • It's not clear what you want to do here. Are you looking to iterate over all the elements in the array and print out their toString() value? – Paul MacGuiheen Jul 10 '16 at 01:07
  • 1
    Do you want to write Foo.toString() by iterating over values or you want to override toString of ArrayList? Take a look at: http://stackoverflow.com/questions/18129505/how-can-i-override-the-tostring-method-of-an-arraylist-in-java – Ali Rokni Jul 10 '16 at 01:15

3 Answers3

1

First of all, it's highly recommended to stay away from raw types. List is a generic type, so you should use it as a generic type.

Then, what you want to do is a mere join operation. If you are using Java 8, you can do

list.stream().collect(Collectors.joining(" -> "))

In plain old Java, you can do

StringBuilder sb = new StringBuilder();
Iterator<T> it = list.iterator();

if (it.hasNext()) sb.append(it.next());
while (it.hasNext()) {
    sb.append(" -> ").append(it.next());
}
String result = sb.toString();
Dici
  • 25,226
  • 7
  • 41
  • 82
1

You need to implement the toString() method from Foo which will be something like:

public String toString(){
    String result  = "" ;
    for(int  i = list.size()-1;i>0;i--){
        result = result+ list.get(i).toString() + " " + ide + " ";
    }
    result = result + list.get(0).toString();
    return result;
}

or, with better performances, as Dici pointed out :

    public String toString(){


    StringBuilder result  = new StringBuilder() ;
    if (!list.isEmpty()){
        for(int  i = list.size()-1;i>0;i--){
            result.append(list.get(i).toString()).append(" ").append(ide).append(" ");
        }
        result.append(list.get(0).toString());
    }
    return result.toString();
}

Then following the way you want to display SomeType you will probably have to implement its own toString method.

minioim
  • 556
  • 3
  • 18
  • String concatenation is slow when done repeatedly to aggregate a result. `StringBuilder` is much faster. Also, your code will fail for an empty list – Dici Jul 10 '16 at 01:19
  • It's been a while since java compiler handle conversion from + operator to StringBuilder if it improves performance. http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1. Yes this code will fail in case of empty list. That's why i said "will be something like" ;) – minioim Jul 10 '16 at 01:30
  • You should not rely on the compiler to write good code in your place. Plus, you're wrong. The compiler will optimize `a + b + c` in a single expression but will not (or may not, depending on the implementaiton) optimize for successive statements with multiple reassignments. I'll create a snippet to prove it to you – Dici Jul 10 '16 at 03:39
  • my bad, i tried it by myself. I thought it would work even with no single expression. anyway I agree about the fact that rely on the compiler is not a good idea. this was only a simple example, easier to understand than StringBuilder. – minioim Jul 10 '16 at 11:00
  • No problem. As a general rule, I would not favour a "simple answer" over the "right answer". Part of Stack Overflow's role is to give people access to the best practices, not just the straightest solution to their problem – Dici Jul 10 '16 at 14:58
  • 1
    Right. Will remember it for next time (i'm juste starting to answer on SO) – minioim Jul 10 '16 at 15:00
  • That's ok, you are willing to take feedback and incorporate it in your answer, which is great. Anyway, good stack-overflowing :p – Dici Jul 10 '16 at 15:02
0

You need create a method toElementString in Foo class.

 public String toElementString(){
        if(list == null || list.size() == 0) return "";
        StringBuffer buffer = new StringBuffer();
        int size = list.size();
        for(int i = 0; i < size;i++){
            buffer.append(list.get(i));
            if(i != (size - 1)){
                buffer.append(" ");
                buffer.append(ide);
                buffer.append(" ");
            }
        }
        System.out.println(buffer.toString());
        return buffer.toString();
    }
Liem Vo
  • 5,149
  • 2
  • 18
  • 16
  • The empty list is not a special case since it will never enter the loop. Also, `StringBuider` is preferred over `StringBuffer` for non-concurrent usages. Finally, you will end up with the separator at the end of the string, which is undesired (something like `item1 sep item2 sep item3 sep`) – Dici Jul 10 '16 at 01:17