java中的容器

接口

两个常用的接口

  1. Collection是接口 :
    Set,List是继承了接口Collection的两个接口,Set中有HashSet实现类;List中有ArrayList实现类和LinkedList实现类。

  2. Map是接口:有HashMap实现类
    (1) Collection

Set:HashSet
List:ArrayList,LinkedList,Vector

(2) MAp:HashMap;

List是有序、可重复的容器

  • 有序:List中每一个元素都有索引标记,可以根据元素的索引标记(在List中的位置)访问元素,从而精确控制这些元素
  • 可重复:List允许加入重复的元素,更切确的讲,List通常允许满足e1.equals(e2)的元素重复加入容器。

1.ArrayList:底层是用数组实现的存储,特点是:查询的效率高,增删效率低,线程不安全,我们一般使用它
2.LinkedList:底层是用链表实现的
3. Vector:底层使用数组实现的,相关的方法都加了同步检查,因此“线程安全,效率低”,
(比如:indexof()方法就增加了synchronize同步标记)
使用要点:

  • 1.需要线程安全时,用Vector
  • 2.不存在线程安全问题时,并且查找较多使用ArrayList(一般使用该方法)
  • 3.不存在自按成安全问题时,增加或者删除元素比较多用LinkedList
    HashSet是没有顺序,不可重复
    Set本身也就是Map,其增加的元素就相当于Map中的key,是不可重复的。
    HashMap
    底层实现是哈希表。哈希表的本质就是数组+链表

HashMap的测试代码:

public class TestTreeMap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<Integer,String> m=new TreeMap<>();
		//按照key递增的方式排序
		m.put(1, "123");
		m.put(3, "asd");
		m.put(4, "poi");
		m.put(2, "abc");
		System.out.println(m);
		for(Integer key:m.keySet()) {
			System.out.println(key+":"+m.get(key));
		}
		Map<Employee,String> tm=new TreeMap<>();
		tm.put(new Employee(100,"li",10000), "好人1");
		tm.put(new Employee(200,"ki",20000), "好人2");
		tm.put(new Employee(300,"yi",30000), "好人3");
		tm.put(new Employee(400,"ei",40000), "好人4");
		System.out.println(tm);
		
		for(Employee key:tm.keySet()) {
			System.out.println(key+":"+tm.get(key));
		}
	}

}


//实现Comparable接口,需要重写compareTo的方法。
class Employee implements Comparable<Employee>{
	int id;
	String name;
	double salary;
	public Employee(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return " id "+id+" name "+name+" salary "+salary;
	}
	public int compareTo(Employee o) {
		//返回负数:小于,返回0:等于,返回整数:大于
		if(this.salary>o.salary) {
			return 1;
		}else if(this.salary<o.salary){
			return -1;
		}else {
			if(this.id>o.id) {
				return 1;
			}else if(this.id<o.id) {
				return -1;
			}else {
				return 0;
			}
		}
	}
}

在List,Set,Map中的各种方法的用法类似

发布了43 篇原创文章 · 获赞 11 · 访问量 2580

猜你喜欢

转载自blog.csdn.net/weixin_43328816/article/details/104317097