java——定義一個功能將ArrayList 集合中的重複元素刪除(java集合七)
阿新 • • 發佈:2019-02-15
定義一個功能將ArrayList 集合中的重複元素刪除
ArrayList 集合中是允許儲存重複元素的
import java.util.ArrayList; import java.util.Iterator; //定義一個功能將ArrayList 集合中的重複元素刪除 public class ArrayListDemes2 { public static void main(String[] args) { // 新建一個容器 ArrayList a = new ArrayList(); //呼叫自定義方法向集合中新增元素 addelements(a); //呼叫自定義方法列印集合 printArrayList(a); //ArrayList 中是可以新增重複元素的 //呼叫自定義方法除集合中的重複元素 System.out.println("--------------------------------------"); ArrayList a1 = removeRepeatElement(a); printArrayList(a1); } //自定義一個列印集合元素的方法 private static void printArrayList(ArrayList a) { Iterator it = a.iterator(); while(it.hasNext()) { Studenti s = (Studenti)it.next(); System.out.println(s.getName()+":"+s.getAge()); } } //定義一個刪除集合中重複元素的方法 private static ArrayList removeRepeatElement(ArrayList a) { ArrayList al = new ArrayList(); Iterator it = a.iterator(); while(it.hasNext()) { Studenti s = (Studenti) it.next(); if(!(al.contains(s))) { //contains 方法依靠的是equals 方法 al.add(s); } } return al; } //定義向集合中新增元素的功能 private static void addelements(ArrayList a) { a.add(new Studenti("kkk",22)); a.add(new Studenti("sss",22)); a.add(new Studenti("www",22)); a.add(new Studenti("kkk",22)); a.add(new Studenti("kkk",22)); } }
class Studenti { private String name; private int age; Studenti(String name ,int age) { this.name=name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public String toString() { return "the student name : +name "+" and age is : "+ age; } public int hashCode() { return name.hashCode()+age*10; } public boolean equals(Object obj) { if(this == obj) return true ;//同一個物件放兩次,直接返回true if(!(obj instanceof Studenti)) throw new ClassCastException("型別錯誤"); Studenti p = (Studenti)obj; return this .name.equals(p.name) && this.age == p.age; } }