如何刪除ArrayList中的重複元素

mischen520發表於2017-10-07
/**
 * 2017年10月7日 上午11:33:57
 * mischen
 */
package com.mischen.cn;

import java.util.ArrayList;
import java.util.Iterator;

class Book{
	int id;
	String  name;
	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 Book(int id, String name) {
		this.id = id;
		this.name = name;
	}
	@Override
	public String toString() {
		return " [書號=" + id + ", 書名=" + name + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Book other = (Book) obj;
		if (id != other.id)
			return false;
		return true;
	}	
}
/**
 * @author mischen
 * 2017年10月7日 上午11:33:57
 */
public class Demo4 {
    public static void main(String[] args){
    	ArrayList list=new ArrayList();
    	list.add(new Book(110, "Java程式設計思想"));
    	list.add(new Book(120, "Java初級"));
    	list.add(new Book(130, "Java高階"));
    	list.add(new Book(110, "深入Java"));
    	ArrayList list2=claerRepeat(list);
    	System.out.println("新集合的元素"+list2);
    }
    public static ArrayList claerRepeat(ArrayList list){
    	ArrayList newsList=new ArrayList<>();
    	Iterator iterator=list.iterator();
    	while(iterator.hasNext()){
    		Book book=(Book) iterator.next();
    		if(!newsList.contains(book)){
    			newsList.add(book);
    		}
    	}
    	return newsList;
    }
}

相關文章