一,编写一个程序,用它来存放5个字符串,然后获取它存放的元素的个数
二,写的简单程序如下:
Person.java
package com.HashSet.java;
public class Person {
public Person(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
private String name;
}
Test1.java
package com.HashSet.java;
import java.util.HashSet;
import java.util.Iterator;
public class Test1 {
public static void main(String [] args)
{
Person p1=new Person("zhangsan");
Person p2=new Person("lisi");
Person p3=new Person("wangwu");
Person p4=new Person("maliu");
Person p5=new Person("liuqi");
HashSet<Person> ha=new HashSet<Person>();
ha.add(p1);
ha.add(p2);
ha.add(p3);
ha.add(p4);
ha.add(p5);
int number=ha.size();
Iterator<Person> iter=ha.iterator();
while(iter.hasNext())
{
Person per=iter.next();
System.out.println("姓名: "+per.getName());
}
System.out.println("一共有"+number+"个元素");
}
}