---
title: "利用 Set 去掉 list中重复值"
author: "gaozhonghui"
date: "2010-11-17T18:31:32Z"
tags: []
categories: ["编程语言"]
slug: "set-list"
draft: false
lastmod: "2011-05-03T12:45:08Z"
id: 814285
url: "https://toptree.iteye.com/blog/814285"
---

今天，在开发的时候遇到了去掉list中的重复值，去掉重复的值分为两种情况：

 

   **1.对原来list顺序不要求**

  

       

```
public static void removeDuplicate(ArrayList arlList) 
{ 
HashSet h = new HashSet(arlList); 
arlList.clear(); 
arlList.addAll(h); 
}
```

 

 

    **2.对原来list顺序不变**

    

```
public static void removeDuplicateWithOrder(ArrayList arlList)    
{    
Set set = new HashSet();    
List newList = new ArrayList();    
for (Iterator iter = arlList.iterator(); iter.hasNext(); )    
{    
Object element = iter.next();    
if (set.add(element)) newList.add(element);    
}    
arlList.clear();    
arlList.addAll(newList);    
}
```

 

 这里主要用了set **add** API 的作用当有了重复值时，返回false