没有跟索引相关的方法,遍历方法:增强for循环,迭代器
放入Integer 类型数据
package wanggng;
?
import java.util.HashSet;
?
public class TestInteger {
public static void main(String[] args) {
//创建一个HashSet集合
HashSet<Integer> hs = new HashSet();
hs.add(19);
System.out.println(hs.add(18));//true这个是输入进去的
System.out.println(hs.add(18));//false这个是没有放进去的
hs.add(15);
hs.add(13);
System.out.println(hs.size());//唯一并且无序
System.out.println(hs);
}
}
?
放入String类型
package wanggng;
?
import java.util.HashSet;
?
public class TestString {
public static void main(){
//创建一个HashSet
HashSet<String> st = new HashSet<>();
st.add("Hello");
st.add("apple");
st.add("banana");
st.add("css");
st.add("apple");
System.out.println(st.size());
System.out.println(st);
}
}
放入自定义的引用类型的数据
package wanggng;
?
import java.util.HashSet;
?
public class TestStudent {
public static void main(String[] args){
HashSet<Student> hs = new HashSet<>();
hs.add(new Student("子义",18));
hs.add(new Student("王刚",19));
hs.add(new Student("子义",18));
hs.add(new Student("金波",21));
hs.add(new Student("付豪",22));
System.out.println(hs.size());
System.out.println(hs);
}
}
package wanggng;
?
public class Student {
private String name;
private int age;
?
public String getName() {
return name;
}
?
public void setName(String name) {
this.name = name;
}
?
public int getAge() {
return age;
}
?
public void setAge(int age) {
this.age = age;
}
?
@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
public Student(String name ,int age){
this.name = name;
this.age = age;
}
}