1

I have a class:

sample.java

class sample

int val;
String str;

constructor

sample(String str,int val)

str=this.str;

val=this.val

test.java

ArrayList<sample> lst=new ArrayList<sample>();

lst.add(new sample("somedata",33)):

lst.add(new sample("somedata",33)):

send(lst) sending arraylist obj over a network.but i was wondering how i can print the values in the arraylist. I tried using iterator but it is only showing object references.

4

5 回答 5

4

Override the toString method in your sample class. You could use:

@Override
public String toString() {
  return "str=" + str + " val=" + val;
}
于 2012-11-02T22:43:58.387 回答
3

The easiest solution to this problem: implement the toString method on your sample class:

@Override
public String toString() {
  return str + ", " + val;
}

Then you'll the field values of each instance.

Otherwise: access the fields from the loop:

for (sample s:lst) {
  System.out.println(s.str + ", " + s.val);
}
于 2012-11-02T22:44:36.903 回答
2

override toString() method in your class

public String toString(){
return str+"," + value;
}

Iterator<Sample> itr = lst.iterator();
while(itr.hasNext()){
system.out.println(itr.next().toString());
}
于 2012-11-02T22:44:17.530 回答
1

Please use class names starting with an upper-case letter. Also your constructor is wrong, it should be

sample(String str,int val) {

this.str=str;

this.val=val

}
于 2012-11-02T23:21:17.697 回答
0

Implement toString and you'll be fine if all you want is just printing objects.

于 2012-11-02T22:45:05.627 回答