本文共 2784 字,大约阅读时间需要 9 分钟。
集合
1.集合Collection是Java JDK提供的一个工具类,用于存储任意数量具有相同属性的对象。一个Collection就是一个Object,包含这个对象中的所有元素。
如下所示,Collection提供了一个根接口,Set和List都继承Collection接口,说明Set和List是一种集合。
Set
public interface Set<E>
extends Collection<E>
在Java 中Set继承自Collection集合。是一个不包含重复元素的Collection,并且最多包含一个 null 元素。
- HashSet
public class HashSet extends AbstractSet<E>
implements Set<E>
, Cloneable, Serializable
HashSet是Set接口的实现类,是以哈希表的形式存储数据,在HashSet中对象的顺序无法保证,如下说明:
public class Main { public static void main(String[] args) { Set testSet = new HashSet (); for(int i=0;i<10;i++){ testSet.add(String.valueOf(i)); } System.out.println(testSet); } } 1 2 3 4 5 6 7 8 9 10
运行结果:
[3, 2, 1, 0, 7, 6, 5, 4, 9, 8] 1
public class Main { public static void main(String[] args) { TestList testList = new TestList();//创建一个TestList对象 Set testSet = new HashSet ();//创建一个Set对象 List storeList = new LinkedList (); storeList = testList.storeList(); for(int i = 0;i
运行结果:
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0][2, 1, 0] 1 2
2.TreeSet
待日后学习..嘿嘿
List
public interface List<E>
extends Collection<E>
在Java 中List继承自Collection集合。是一个有序的集合,可以通过对象的位置(索引)去访问对象。允许集合中存在重复的元素,并且允许存在重复的null元素。
1. ArrayList
public class ArrayList<E>
extends AbstractList<E>
implements List<E>
,RandomAccess,Cloneable,Serializable
ArrayList是List接口的实现类。实现了List接口的大小可变的数组,列表的容量随着元素的增加而增加,并允许包括 null 在内的所有元素。可以通过一些方法自定义列表的数组大小,如下所示:
public class TestList { public List storeList(){ List testList = new ArrayList (); for(int i=0;i<10;i++){ int j = i%3; testList.add(String.valueOf(j)); } return testList; }} 1 2 3 4 5 6 7 8 9 10
2.LinkedList
public class LinkedList extends AbstractSequentialList<E>
implements List<E>
,Deque<E>
,Cloneable, Serializable
LinkedList也是List接口的一个实现类。实现了链接列表,允许null在内的所有元素,并且元素是有序的。并且可将链表用作队列、堆栈、双向队列。
练习如下:
public class TestLinkedList { public static void main(String[] args){ System.out.print("H"); LinkedList testLinkedList = new LinkedList();//定义一个默认长度为10的LinkedList列表 for(int i = 0;i<10;i++){ testLinkedList.add(i);//将元素添加到列表的末尾 } testLinkedList.add(3,10); //表示在位置3,添加元素10 testLinkedList.addFirst(11);//在列表的首位添加元素 testLinkedList.addLast(12);//在列表的末位添加元素 System.out.println(testLinkedList); Object i = testLinkedList.get(3);//get()方法是得到某一位置的元素 System.out.println(i); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
运行结果:
[11, 0, 1, 2, 10, 3, 4, 5, 6, 7, 8, 9, 12]2