util包的常用类及其方法(下)

一。Collection及其子接口List,Set

Collection是List和Set的父接口。Java语言不仅可以用类说明引用类型也可以用接口说明引用类型。该类型引用所指向的对象必须实施了该接口。

1.1List接口

List接口引用存放的是有序的元素,元素可以重复。

import java.util.*;

public class Test{

public static void main(String[] agrs){

//容器aa的引用为List类型,实施为ArrayList类,即引用和实施相分离。<>定义容器中元素的类型,类型必须为类,如存储的元素为整数,必须

List<String> aa=new ArrayList<String>();

//增加新元素

aa.add("苹果");

aa.add("橘子");

aa.add("香蕉");

aa.add("桃子");

aa.add("苹果");

//aa.get(int index)根据索引获得元素

System.out.println(aa.get(2));

//aa.remove(int index)根据索引删除元素

aa.remove(2);

System.out.println(aa.size());

//删除全部元素

aa.clear();

}

1.2Set接口

与List接口不一样,Set接口的元素没有顺序,元素也不可重复。

import java.util.*;

public class Test{

public static void main(String[] agrs){

Set<Integer> aa=new HashSet<Integer>();

aa.add(new Integer(2));

aa.add(new Integer(3));

aa.add(new Integer(4));

aa.add(new Integer(5));

aa.remove(new Integer(5));

System.out.println(aa.size());

}

}

1.3iterator方法

Collection接口有iterator()方法,通过iterator()方法生成一个循环器,通过.next()方法,可以返回下一个元素,直到穷尽。

import java.util.*;

public class Test{

public static void main(String[] agrs){

Set<Integer> aa=new HashSet<Integer>();

aa.add(new Integer(2));

aa.add(new Integer(3));

aa.add(new Integer(4));

aa.add(new Integer(5));

//生成循环器

Iterator i=aa.iterator()

//如果循环器有下一个元素,将其打印出来

while(i.hasNext()){

System.out.println(i.next());

}

}

}

二.Map接口

Map接口存储的元素为键值对。通过键可以得到值。

import java.util.*;

public class Test{

public static void main(String[] agrs){

Map<String ,Integer>  map=new HashMap<String ,Integer>();

map.put("niuhaitao",1);

map.put("maxiaohui",2);

map.put("niuzitong",3);

System.out.println(map.get("niuzitong");

}

}

Map中,put()方法添加元素,get()方法获得指定键的值。

keySet()方法将所有的键转化为Set

values()方法将所有的值转化为List

通过这两种方法将Map转化为Collection类。

三。Vector类

Vector类与ArrayList类、LinkedList类似,不同点在于Vector类时线程同步的。如果需要线程之间互不干扰,用Vector类是最好的。

3.1Vector类的构造器

Vector():创建一个空的Vector类对象,初始容量为10,容量增量为0

Vector(Collection c):根据Collection c创建一个Vector类对象

Vector(int initialCapacity):创建一个Vector类对象,初始容量为initialCapacity,增量为0

Vector(int initialCapacity,int capacityIcrement):创建一个Vector类对象,初始容量为initialCapacity,容量增量为capacityIncrement

3.2常用方法

int size():返回元素的数量,需要与capacity()方法区分开,后者返回的是容量,即最多可容纳的数量

boolean isEmpty():判断是否为空

void clear():删除所有的元素

boolean add(Object element):增加元素

 Object remove(int index);删除指定索引的元素

Object get(int index):返回指定索引的元素

Object set(int index,Object elemen):指定索引位置设置特定元素

int indexOf(Object element):返回指定元素的索引

addElement():增加元素到Vector对象的末尾处

insertElementAt(int index):在指定索引位置插入元素

setElementAt(Object element,int index):指定索引位置设定特定对象

elementAt(int index):获得指定索引位置的元素

firstElement():获得第一个元素

lastElement():获得最后一个元素

removeAllElement():删除所有元素,同clear()方法

copyInto(Object[] array):将所有元素复制到一个数组

setSize(int newSize):根据newSize值设定新容量

原文地址:https://www.cnblogs.com/hitnmg/p/9216861.html