去除重复字符串
public class List01 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
list.add("李四");
list.add("王五");
System.out.println("-----去除重复元素之前------");
Iterator<String> it = list.iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str);
}
//开始去除重复元素
//创建新的集合
List<String> newList = new ArrayList<String>();
//遍历旧集合
for(String str : list){
//如果旧集合中不包含指定元素,则添加到新集合中
if(!newList.contains(str))
newList.add(str);
}
System.out.println("-----去除重复元素之后------");
//遍历新集合
Iterator<String> newIt = newList.iterator();
while(newIt.hasNext()){
System.out.println(newIt.next());
}
}
}
结果
-----去除重复元素之前------
张三
李四
王五
赵六
李四
王五
-----去除重复元素之后------
张三
李四
王五
赵六
去除重复对象
class Book{
private String name;
private double price;
public Book() {
}
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean equals(Object obj) {
if(this==obj)
return true;
if(obj==null)
return false;
if(!(obj instanceof Book))
return false;
Book book = (Book)obj;
if(this.price != book.price)
return false;
if(this.name==null){
if(book.name!=null)
return false;
}else if(!this.name.equals(book.name))
return false;
return true;
}
@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}
}
public class List02 {
public static void main(String[] args) {
List<Book> list = new ArrayList<Book>();
Book b1 = new Book("java编程思想",89.8);
Book b2 = new Book("深入理解jvm",79.8);
Book b3 = new Book("算法导论",69.9);
Book b4 = new Book("面向对象程序设计",49.9);
Book b5 = new Book("java编程思想",89.8);
Book b6 = new Book("深入理解jvm",79.8);
Book b7 = new Book("算法导论",69.9);
Book b8 = new Book("面向对象程序设计",49.9);
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
list.add(b6);
list.add(b7);
list.add(b8);
List<Book> newList = new ArrayList<Book>();
Iterator<Book> it =list.iterator();
while(it.hasNext()){
Book book = it.next();
if(!newList.contains(book))
newList.add(book);
}
Iterator<Book> newIt = newList.iterator();
while(newIt.hasNext()){
System.out.println(newIt.next());
}
}
}
结果
Book [name=深入理解jvm, price=79.8]
Book [name=算法导论, price=69.9]
Book [name=面向对象程序设计, price=49.9]
Book [name=null, price=49.9]