本文共 3106 字,大约阅读时间需要 10 分钟。
官方文档的解释是这样的
An array is a container object that holds a fixed number of values of a single type.
Array是一个容器,储存了一定数量,单一类型的对象
The length of an array is established when the array is created. After creation, its length is fixed.
Array的长度在其被创建时就确认了。
Array 例子:
int intArray[]={1,2,3}; System.out.print(intArray[1]);
Array 这个容器可以储存多个元素,并且提供给我们方便的下标访问
另外,Array 储存的是对象,说明并不局限于 int ,如下:
char charArray[]= { 'k','o'}; System.out.print(charArray);
output:ko
String charArray[]= { "ss","ww"}; System.out.print(charArray[0]);
output:ss
Array 中的方法:
equals():比较两个array是否相等。array拥有相同元素个数,且所有对应元素两两相等。
fill():将值填入array中。 sort():用来对array进行排序。 binarySearch():在排好序的array中寻找元素。 System.arraycopy():array的复制。
但是,Array 的有其局限性:
1.创建过后不可再添加对象
所以,人们又创造了List(允许对对象进行增删改查等)
2.只能用下标访问元素
所以,人们又创建了Map(可以通过key来获取value)
3.人们对容器内的元素要求其不能重复
所以,人们创造了Set
由于我们的需求,我们创建了这样那样的类,我们称之为 “集合” — 对应了我们的collection 接口
collection 中的方法
boolean add(Object o) :增加一个对象的引用
void clear():清空对象的引用 boolean isEmpty() :判断集合是否为空 boolean contains(Object o) : 判断集合中是否包含特定对象的引用 Iterartor iterator() :返回一个Iterator用来遍历集合中的元素 boolean remove(Object o) :删除一个对象的引用 int size() :返回元素的数量 Object[] toArray() : 返回一个数组,该数组中包括集合中的所有元素
List 和Set 就是继承了上面的collection 接口
除此之外,我们还得认识到一个点
就是List、Set、Map 都只是接口,不能直接实例化
只有其具象类(也就是implement 实现了List 等接口的类)才可以实例化
举例:
Set hs=new HashSet();List al=new ArrayList();Map hm =new HashMap();
如上文所说,List 可以进行增删改查
我们用的List 具象类主要是:ArrayList 和LinkedList
两个类各有特点
示例:
List a=new ArrayList(); // ArrayList contain the Object not the only typea.add(1);a.add("world");System.out.print(a);
output: [1,world]
Set 内储存的是对象的引用,不重复
我们常用的Set 具象类有:HashSet 和TreeSet
示例:
Set a =new TreeSet(); //sort elements automaticallya.add(2);a.add(1);System.out.print(a);
output:[1,2]
官方文档的阐述:
A Map is an object that maps keys to values.
Map是由键值对表示的对象
常用的类:HashMap、TreeMap、LinkedHashMap
LinkedHashMap 和HashMap 的区别
看示例:
Map a =new HashMap(); a.put(2, "a"); a.put(1, "b"); a.put(10, "c");a.put(4, "d"); a.put(5, "e"); System.out.print(a);
output:{1=b, 2=a, 4=d, 5=e, 10=c}
Map a =new LinkedHashMap(); //don't need to confirm the typea.put(2, "a"); //TreeMap will auto sort of key(not value) for you a.put(1, "b"); //int is also a class a.put(10, "c"); //update a.put(4, "d"); a.put(5, "e");System.out.print(a);
output:{2=a, 1=b, 10=c, 4=d, 5=e}
以上,可以看出来LinkedHashMap是按插入顺序排列元素的,而HashMap 则是无序的
另外,因为HashMap 无序, 所以导致了另一个问题,就是map 的复制
来看一段代码:
Map a =new HashMap(); a.put(2, "a"); a.put(1, "b"); a.put(10, "c"); a.put(4, "d"); a.put(5, "e"); System.out.println(a);Map b= new HashMap(a);System.out.println(b);
output:{1=b, 2=a, 4=d, 5=e, 10=c}
{1=b, 2=a, 10=c, 4=d, 5=e}
可以发现这样创建的一个新的HashMap居然是不同的!
而LinkedHashMap 可以解决这个问题,复制出一个一样的LinkedHashMap~
总结一下:
1.List,Set,Map 都是人们基于某些需求而创造的接口,并不能直接实例化
2.一般情况下,都是使用HashList,HashSet,HashMap 因为速度快
有特殊需求再选择TreeSet 等
3.关于上面Hash 等的具体实现,大家可以自行查阅资料了解
我觉得了解得够深入,你用起来才会更顺手,我之后可能也会再写文章来分享
转载地址:http://soiyb.baihongyu.com/