<Java集合框架的四大接口>
Collection:List列表,Set集(继承自Collection接口)。
List特点:元素有放入顺序,可重复。
Set特点:元素无放入顺序,不可重复。
Map特点:元素按键值对存储,无放入顺序。
接口的常用实现类:ArrayList、LinkedList、Vector、HashSet、LinkedHashSet、TreeSet、HashMap、LinkedHashMap、TreeMap、HashTable
一、List接口
是一个有序集合,继承自Collection接口。现已知常用实现类有:ArrayList、LinkedList、Vector。
- 常用方法:
add():在列表的最后添加元素;
add(index,obj):在列表的指定位置添加元素;
size():返回当前列表的元素个数
get(int index):返回下标为index的元素;
clear():清除列表中所有元素;
isEmpty():检测列表是否为空;返回true/false;
contains():传入一个对象,检测列表中是否含有该对象;
indexOf():传入一个对象,返回该对象在列表中首次出现的地址;
lastInsevOf():传入一个对象,返回该对象在列表中最后一次出现的地址;
remove():传入一个下标,或者一个对象,删除指定元素;如果删除指定对象,需要重写equals()方法,比对传入的对象是不是属于原列表,如果属于,结果返回true;
set(index,obj):用新传入的对象,将指定位置的元素替换掉,返回被替换前的元素对象;
subList():截取一个子列表返回List类型;
toArray():将列表转为数组,返回一个Object[]类型;
iterator():使用迭代器遍历。
- 如何输出List列表?
a. for循环;
b. foreach遍历(比较常用);
c. 使用迭代器遍历列表;
- List接口的常用实现类:
ArrayList和LinkedList实现类是继承自List接口的,所以List的常用方法它们也是适用的。
a. ArrayList
ArrayList实现了一个长度可变的数组,在内存空间中开辟一串连续的空间。
b. LinkedList
LinkedList使用链表结构存储数据,在插入和删除元素是速度非常快。
// ArrayList实现类
ArrayList<String> list1 = new ArrayList<String>();list1.add("第一条数据");list1.add("第二条数据");list1.add("第三条数据");list1.add("第四条数据");list1.add("第五条数据");list1.add("第三条数据");list1.add(2,"第六条数据"); // 在第三条数据后添加“第六条数据”
System.out.println(list1.size()); // 返回列表长度
System.out.println(list1.get(2)); // 返回“第六条数据”
// list1.clear(); //清除所有数据
System.out.println(list1.isEmpty()); // 返回false
System.out.println(list1.contains("第一条数据")); // 返回true
System.out.println(list1.indexOf("第三条数据")); // 返回3
System.out.println(list1.lastIndexOf("第三条数据")); // 返回6
System.out.println(list1.remove(1)); // 删除“第二条数据”
System.out.println(list1.set(0,"替换第一条数据")); // 替换第一条数据
List list=list1.subList(2, 5); // 截取第三到第五条数据,返回List
System.out.println(list1.toString()); // 转成数组
// LinkedList实现类
LinkedList<News> list2=new LinkedList<News>();list2.add(new News(1,"xxxxxxx","赵"));list2.add(new News(2,"sssssss","钱"));list2.add(new News(3,"yyyyyyy","孙"));list2.add(new News(4,"nnnnnnn","李"));list2.add(new News(5,"rrrrrrr","周"));30 System.out.println(list2.contains(new News(3,"yyyyyyy","孙"))); // 返回为true;重写equals()方法;如果不重写equals()方法,返回为false;
System.out.println(list2.remove(new News(1,"xxxxxxx","赵"))); // 返回为true
/*
* 使用for循环遍历
*/
for(
int i = 0;i<list1.size();i++)
{
if (list1.get(i) instanceof String) { // 判断传入的数据属不属于String类型
String str = list1.get(i);
System.out.println(str);
}
}
/*
* foreach遍历
*/
for(
News news:list2)
{
System.out.println(news.getId() + " " + news.getTitle() + "\t" + news.getAuthor());
}
/*
* 迭代器遍历
*/
Iterator<String> iter=list.iterator();while(iter.hasNext())
{ //判断list有没有下一条
String s=iter.next(); //字符串取到下一条
System.out.println(s);
}
/**
* News类
*/
class News {
private int id;
private String title;
private String author;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
News other = (News) obj;
if (author == null) {
return false;
} else if (!author.equals(other.author))
return false;
if (id != other.id)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
public News() {
super();
}
public News(int id, String title, String author) {
super();
this.id = id;
this.title = title;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
二、Set接口
- 常用方法:
与List接口基本相同。但是Set接口中的元素是无序的,因此没有与下标有关的方法。例如:get(index)、remove(index)、add(index,obj)
- Set接口的现已知常用实现类有:
HashSet、LinkedHashSet、TreeSet
- HashSet
底层是HashMap的相关方法,传入数据后,根据数据的hashCode进行散列运算,得到一个散列值后再进行运算,确定元素在序列中存储的位置。
所以,使用HashSet存数据必须在实体类中重写hashCode和equals方法!!
//HashSet无序的
2 Set<String> set1=new HashSet<String>();
3 set1.add("set1");
4 set1.add("set2");
5 set1.add("set3");
6 set1.add("set4");
7 set1.add("set5");
8
9 //foreach遍历
10 for (String set : set1) {
11 System.out.println(set);
12 }
- LinkedHashSet
在HashSet的基础上,新增了一个链表。用链表来记录HashSet种元素放入的顺序;HashSet依然是无序的,但链表会按照存入的顺序存储。
// LinkedHashSet按照放入的顺序输出
Set<Person> set2 = new LinkedHashSet<Person>();
// set2.addAll(set1); //追加set1的所有数据
set2.add(new Person(1,"红"));
set2.add(new Person(2,"黄"));
set2.add(new Person(3,"蓝"));
set2.add(new Person(4,"绿"));s
set2.add(new Person(4,"绿"));
// 迭代器遍历
Iterator<Person> iter=set2.iterator();while(iter.hasNext())
{
Person p = iter.next();
System.out.println(p.getId() + "\t" + p.getName());
}
class Person {
private int id;
private String name;
/*
* 如果不重写hashCode和equals方法,存入相同数据时将无法比对
*
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Person() {
super();
}
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- TreeSet
将存入的数据,进行排序,然后输出。
如果传入的是一个实体对象,那么需要传入比较器:实体类实现Comparable接口,并重写CompareTo方法;
// TreeSet从小到大输出。存入元素,默认升序排序;存入实体对象,需要传入比较器
Set<Person> set3 = new TreeSet<Person>();
set3.add(new Person(11,"a"));
set3.add(new Person(22,"b"));
set3.add(new Person(33,"c"));
set3.add(new Person(44,"d"));
// 迭代器遍历
Iterator<Person> iter=set3.iterator();while(iter.hasNext())
{
Person p = iter.next();
System.out.println(p.getId() + "\t" + p.getName());
}
class Person implements Comparable { // 实现
private int id;
private String name;
// compareTo方法判断传入的对象和已有对象
@Override
public int compareTo(Object o) {
Person p = null;
if (o instanceof Person) {
p = (Person) o;
} else {
return 0;
}
return this.id - p.getId(); // 为正数,升序;为负数,降序;等于0,位置不变
}
public Person() {
super();
}
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
三、Map接口
- Map接口的特点:
以键值对的形式存储数据,以键取值。键不能重复,值可以重复。
- Map接口的现已知常用实现类有:
HashMap、HashTable、LinkedHashMap、TreeMap
- 常用方法:
put(key,value):向Map的最后追加一个键值对;
get(key):通过键,取到一个值;
clear():清除Map中的所有数据;
containsKey(key):检测是否包含指定的键;
containsValue(obj):检测是否包含指定的值;
replace():替换指定键的值;
- 遍历Map
a. keySet():返回Set,先取键,再取值;
b. values():返回Collection,直接取值;
c. 取代一个entry键值对,返回Set<Entry<>>;
Map<String, String> map1 = new HashMap<String, String>();map1.put("01","aaaaaa");map1.put("02","bbbbbb");map1.put("03","cccccc");map1.put("04","dddddd");
// map1.clear(); //清除所有数据
System.out.println(map1.containsKey("01")); // 返回true
System.out.println(map1.containsValue("aaaa")); // 返回false
System.out.println(map1.replace("03","dddddd")); // 将cccccc替换为dddddd
System.out.println(map1.get("02")); // 返回bbbbbb
/**
* 遍历Map的方式一,先取键,再取值
*/
Set<String> keys = map1.keySet(); // 取到所有键
Iterator<String> iter=keys.iterator();while(iter.hasNext())
{ // 迭代器遍历取到每一个键
String key = iter.next();
System.out.println(key + " " + map1.get(key));
// key:取到键
// map1.get(key):取到每个键对应的值
}
/**
* 遍历Map的方式二,直接取值;只能取到值
*/
Collection<String> values = map1.values();
Iterator<String> iter1 = values.iterator();while(iter1.hasNext())
{
System.out.println(iter1.next());
}
/**
* 遍历Map的方式三,取到一个entry键值对
*/
Set<Entry<String, String>> set = map1.entrySet();
Iterator<Entry<String, String>> iter2 = set.iterator();while(iter2.hasNext())
{
Entry<String, String> entry = iter2.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}
- LinkedHashMap
可以使用列表,记录数据放入的次序,输出的顺序与放入的顺序一致。与LinkEDHashSet一样。
- TreeMap
根据键的顺序,进行排序后输出。与TreeSet。
如果传入的是实体对象,必须重写比较函数。
- HashMap和HashTable的区别?
a. HashTable是线程安全的,HashMap是线程不安全的;
b. HashTable的键不能为null,HashMap的键可以为null;
c. HashTable继承自Dirctionary字典类,HashMap继承自abstract类;
d. 扩容大小:HashTable两倍,HashMap两倍加一;
e. 初始容量:HashTable为11,HashMap为16;两者的填充因子默认都是0.75;