一、Set接口
Set接口是Collection的子接口,没有定义新的方法,常用的一个实现该接口的类为HashSet
常用方法:
-
boolean | addAll(Collection<? extends E> c) |
-
boolean | retainAll(Collection<?> c) |
package Container;
import java.util.HashSet;
import java.util.Set;
public class TestSet {
public static void main(String args[]){
Set s1=new HashSet();
s1.add("a");s1.add("b");s1.add("c");
Set s2=new HashSet();
s2.add("d");s2.add("b");s2.add("a");
Set sn=new HashSet(s1);//将s1复制到sn,因为通过要进行两个操作,addaAll和retainAll S1会被覆盖
s1.addAll(s2);
sn.retainAll(s2);
System.out.println(s1);
System.out.println(s2);
}
}
结果:[d, b, c, a]
[d, b, a]
二、List接口
List接口是Collection接口的子接口,实现该接口的主要的类有:ArrayList和LinkedList,其中ArrayList是底层利用数组实现的容器,LinkedList是底层利用链表实现的容器。
常用方法
-
E | set(int index, E element) |
-
package Container;
import java.util.ArrayList;
import java.util.List;
public class TestList1 {
public static void main(String args[]){
List l1=new ArrayList();
for(int i=0;i<5;i++)
l1.add("a"+i);
System.out.println(l1);
l1.set(3, "a100");
System.out.println(l1);
System.out.println(l1.get(4));
}
}
结果:[a0, a1, a2, a3, a4]
[a0, a1, a2, a100, a4]
a4
Collections类
java.util.Collections:提供了一些静态方法实现了基于List容器的一些算法
常用算法:
static
| sort(List<T> list, Comparator<? super T> c) |
static void | shuffle(List<?> list) |
static
| binarySearch(List<? extends Comparable<? super T>> list, T key) |
static void | reverse(List<?> lis |
static
| copy(List<? super T> dest, List<? extends T> src |
package Container;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class TestList2 {
public static void main(String args[]){
List l2=new LinkedList();
for (int i=0;i<=5;i++)
l2.add("a"+i);
System.out.println(l2);
Collections.sort(l2);//静态方法,类名。方法
System.out.println(l2);
Collections.reverse(l2);
System.out.println(l2);
Collections.shuffle(l2);
System.out.println(l2);
}
}
结果:[a0, a1, a2, a3, a4, a5]
[a0, a1, a2, a3, a4, a5]
[a5, a4, a3, a2, a1, a0]
[a5, a4, a2, a3, a1, a0]
三、Map接口
实现Map接口的类常用来存储键-值对,Map接口的实现类有HashMap和TreeMap
常用方法:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class TestMap {
public static void main(String args[]){
Map m1=new HashMap();
Map m2=new TreeMap();
m1.put("1", 1);
m1.put("2", new Integer(2));
System.out.println(m1);
m2.put("first", "1");
m2.put("second", "2");
System.out.println(m2);
m1.put("1", "first");
System.out.println(m1);
System.out.println(m1.hashCode());
}
}