HashSet存入对象怎么取出对象的值
我的代码如下:publicclassHashSetTest{publicstaticvoidmain(Stringargs[]){Students1=newStudent...
我的代码如下:
public class HashSetTest{
public static void main(String args[]){
Student s1 = new Student(1,"zhang san1");
Student s2 = new Student(2,"zhang san2");
Student s3 = new Student(3,"zhang san3");
Student s;
Set hs = new HashSet();
hs.add(s1);
hs.add(s2);
hs.add(s3);
Iterator it = hs.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}
class Student{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
}
不知道怎样从hs中取出studnt对象的值,请大家指点一下。 展开
public class HashSetTest{
public static void main(String args[]){
Student s1 = new Student(1,"zhang san1");
Student s2 = new Student(2,"zhang san2");
Student s3 = new Student(3,"zhang san3");
Student s;
Set hs = new HashSet();
hs.add(s1);
hs.add(s2);
hs.add(s3);
Iterator it = hs.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}
class Student{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
}
不知道怎样从hs中取出studnt对象的值,请大家指点一下。 展开
3个回答
展开全部
你是想说输出num和name么;两种方法:
一
Iterator it = hs.iterator();
while(it.hasNext())
Student s = (Student)it.next();
System.out.println(s.num+"NAME : "+s.name);
}
二 在Student类中复写toString()方法:
class Student{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
public String toStrong(){
return "num :"+this.num +" name: "+this.name ;
}
}
采用二方法较佳,此时直接输出对象即可;
while(it.hasNext())
Student s = (Student)it.next();//需要强制转换
System.out.println(s);
}
一
Iterator it = hs.iterator();
while(it.hasNext())
Student s = (Student)it.next();
System.out.println(s.num+"NAME : "+s.name);
}
二 在Student类中复写toString()方法:
class Student{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
public String toStrong(){
return "num :"+this.num +" name: "+this.name ;
}
}
采用二方法较佳,此时直接输出对象即可;
while(it.hasNext())
Student s = (Student)it.next();//需要强制转换
System.out.println(s);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Iterator it = hs.iterator();
while(it.hasNext())
//System.out.println(it.next());
Student s = (Student)it.next();
}
while(it.hasNext())
//System.out.println(it.next());
Student s = (Student)it.next();
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Iterator iterator = set.iterator();
while(iterator.hasNext()){
Student student = (Student)iterator.next();
}
while(iterator.hasNext()){
Student student = (Student)iterator.next();
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询