0

I have a class like this in Java:

public class Wrapper {
    public static List<Type> list;

    @Override
    public String toString() {
        return "List: " + this.list;
    }

    public static void main(String[] args) {
        Wrapper w = new Wrapper();
        System.out.println(w);
    }
}

and a class like this:

public class Type {
    private static String name;

    public Type(String n) {
        this.name = n;
    }

    @Override
    public String toString() {
        return this.name;
    }
}

Instead of getting the name of each item, I get the name of the last item for each item in the array. Any suggestions?

user1947561
  • 1,117
  • 2
  • 8
  • 13
  • 3
    try remove that `static` word for the variable name and try it again ;) – kucing_terbang Dec 02 '15 at 04:41
  • I would agree that this is a duplicate, but to be fair, I don't think that I would've found that answer from Googling/searching on SO, as I thought this was a problem of toString... – user1947561 Dec 02 '15 at 04:52
  • in class `Type` `private static String name;` should be `private String name`. its not a static field (or shouldn't be the way you are using it in the constructor. – ptierno Dec 02 '15 at 04:59

2 Answers2

6

in your Type class you are marking your name as static so when printing type.toString() you always have only one value. And if you want to print all member of your list, use:

for(Type t : list){
   System.out.print(t.toString());
}
Mingo.Link
  • 168
  • 5
-1
@Override
public String toString() {
    String s = "";
    for(Type t : list) {
        s += t;
    }
    return s;
}