欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

用ArrayList存储用户对象,并删除里面的重复对象,arraylist存储

来源: javaer 分享于  点击 15657 次 点评:84

用ArrayList存储用户对象,并删除里面的重复对象,arraylist存储


#日常练习

用ArrayList存储用户对象,并删除里面的重复对象

package Collection;

import java.util.*;

/*用ArrayList存储用户对象,并删除里面的重复对象(用户注册时可能有用)
 * 步骤:1,建立通用户对象,
 *   2,建立ArrayList集合存储,
 *   3,比较。
 * */




public class ArrayListTest {
	public static ArrayList<Administrator> singleElement(ArrayList<Administrator> al) {
		ArrayList<Administrator> tempAl = new ArrayList<Administrator>();
		
		for(Iterator<Administrator> it = al.iterator();it.hasNext();)
		{
			Administrator adm = it.next();
			//List中的contains()底层时调用equals()的,
			//可以通过复写相应对象的equals()方法来让contains()按自己的规则来执行;
			if(!(tempAl.contains(adm))) {
				tempAl.add(adm);
			}
		}
		return tempAl;
		
	}

	public static void main(String[] args) {
		
		ArrayList<Administrator> al = new ArrayList<Administrator>();
		al.add(new Administrator(123,"person1"));
		al.add(new Administrator(456,"person2"));
		al.add(new Administrator(456,"person2"));
		al.add(new Administrator(789,"person3"));
		al.add(new Administrator(769,"person3"));
		al.add(new Administrator(147,"person4"));
		al.add(new Administrator(147,"person4"));
		al = singleElement(al);
		
		for(Iterator<Administrator> it = al.iterator();it.hasNext();) {
			//存储时会将Administrator对象向上转型为Object
			//所以在这里需要将它强制转型为Administrator对象
			//更新:学了泛型就不需要了
			Administrator a = it.next();
			System.out.println("conut:"+a.getCount()+"    name:"+a.getName());
		}
		


	}

}

被调用类:
package Collection;
//将自定义类存入TreeSet中时,自定义类必须实现Comparable接口
class Administrator implements Comparable<Administrator>{


	private int count;
	private String name;
	Administrator(int count,String name){
		this.count = count;
		this.name = name;
	}
	//复写Object类中compareTo方法,定义自己的比较方法。
	public int compareTo(Administrator adm) {
		if(!(adm instanceof Administrator)) {
			throw new RuntimeException("传入的类类型错误!");
		}
		
		if(this.getCount() > adm.getCount()) {
			return 1;
		}
		if(this.getCount() == adm.getCount()) {
			this.getName().compareTo(adm.getName());
			return 0;
		}
		return -1;
		
	}

	public int hashCode() {
		return this.count+this.name.hashCode();
	}

	public boolean equals(Object obj) {
		if(!(obj instanceof Administrator)) {
			throw new RuntimeException("传入的类类型错误!");
		}
		Administrator adm = (Administrator)obj;
		//按照账号和姓名都相同时判断为相同对象;
		return(this.count == adm.count && this.name.equals(adm.name)) ;
		
	}
	
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}







相关文章

    暂无相关文章

用户点评