set
package com.chen.集合框架和泛型.Collection.set;
import com.chen.集合框架和泛型.Collection.NewTitle;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created by chen on 2018/3/16.
*/
public class LearnHashSet {
public static void main(String[] args) {
NewTitle newTitle1 = new NewTitle(1 , "linkedList1" , "LinkedList1" );
NewTitle newTitle2 = new NewTitle(1 , "linkedList2" , "LinkedList2" );
Set hashSet = new HashSet();
System.out .println("***添加两个newTitle1,实际只添加了一个,元素值唯一" );
hashSet.add(newTitle1);
hashSet.add(newTitle1);
for (Object obj : hashSet) {
System.out .println(((NewTitle) obj).getName());
}
hashSet.add(newTitle2);
System.out .println("新闻条数:" + hashSet.size());
System.out .println("newTitle2是否存在:" + hashSet.contains(newTitle2));
System.out .println("***移除linkedList1对象***" );
hashSet.remove(newTitle1);
System.out .println("集合是否为空:" + hashSet.isEmpty());
System.out .println("***遍历结合***" );
for (Object obj : hashSet) {
System.out .println(((NewTitle) obj).getName());
}
System.out .println("*********Iterator接口*********" );
System.out .println("***获取集合迭代器***" );
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()){
System.out .println(((NewTitle)iterator.next()).getName());
}
}
}
package com.chen.集合框架和泛型.Collection;
/**
* Created by chen on 2018/3/16.
*/
public class NewTitle {
private int id ;
private String name ;
private String title ;
public NewTitle(int id, String name, String title) {
this .id = id;
this .name = name;
this .title = title;
}
public int getId() {
return id ;
}
public void setId(int id) {
this .id = id;
}
public String getName() {
return name ;
}
public void setName(String name) {
this .name = name;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this .title = title;
}
}