标签:arraylist tor ext for ide -- str work can
package Homework;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
/**
* list集合是否可以包含重复元素?
* 如果可以,请写一个算法,用于将list集合内重复元素剔除。
* @author 张致远
*
*/
public class Homework2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List list= new ArrayList();
list.add("student1");
list.add("student2");
list.add("student2");
list.add("student3");
list.add("student4");
list.add("student4");
list.add("student2");
list.add("student3");
list.add("student1");
int hashobj[]=new int[list.size()]; //建立hash码数组,存储元素hashcode
for(int i=0;i<list.size();i++){
Object object2 = list.get(i);
hashobj[i]=object2.hashCode(); //得出hash码,存在数组中
for(int j=i;j>=0;j--){ //遍历之前元素hash码,有相同的就剔除
if(hashobj[i]==hashobj[j]){
list.remove(j); //剔除
}
}
System.out.println(object2);
}
System.out.println("-----------------");
for (Iterator iterator = list.iterator(); iterator.hasNext();) { //迭代器
Object object = (Object) iterator.next();
System.out.println(object);
}
// System.out.println("-----------------");
// for (Iterator iterator = list.iterator(); iterator.hasNext();) {
// Object object = (Object) iterator.next();
// int hash=object.hashCode();
// System.out.println("hashobj="+hash);
//// System.out.println(object);
// }
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
标签:arraylist tor ext for ide -- str work can
原文地址:http://www.cnblogs.com/Chandelier/p/6341611.html