定义:对象的容器,实现了对对象的常用操作,类似数组的功能。
和数组的区别:
位置:java.util.*
特点:代表一组任意类型的对象,无序,无下标,不能重复
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//添加元素
collection.add("红豆");
collection.add("我愿意");
collection.add("旋木");
collection.add("只爱陌生人");
collection.add("幽兰操");
System.out.println("元素个数"+collection.size());
System.out.println(collection);
//删除元素
collection.remove("旋木");
System.out.println("元素个数"+collection.size());
System.out.println(collection);
//遍历元素
//增强for循环
System.out.println("==============使用增强for循环遍历元素==============");
for (Object o : collection) {
System.out.println(o);
}
//专门用来遍历集合的一种方式
System.out.println("==============使用迭代器遍历元素==============");
//hasNext()有无下个元素 next()获取下个元素 remove()删除当前元素 迭代过程中不能使用collection.remove进行删除
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
String string = (String) iterator.next();
System.out.println(string);
iterator.remove();
}
System.out.println("元素个数"+collection.size());
//判断
System.out.println("==============判断==============");
System.out.println(collection.contains("旋木"));
}
}
public class Couple {
private int age;
private String name;
public Couple(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Couple ["+"name="+this.name+","+"age="+this.age+"]";
}
}
public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
//添加数据
Couple c1 = new Couple(26,"AB");
Couple c2 = new Couple(27,"CD");
Couple c3 = new Couple(28,"EF");
collection.add(c1);
collection.add(c2);
collection.add(c3);
System.out.println(collection.size());
System.out.println(collection.toString());
//删除数据
//collection.remove(c1);
//System.out.println(collection.size());
//collection.clear();
//System.out.println(collection.size());
//遍历
for (Object o : collection) {
System.out.println(o);
}
System.out.println("==============使用迭代器遍历元素==============");
//迭代器
Iterator iterator = collection.iterator();
int i = 0;
while (iterator.hasNext()){
System.out.println(i);
Couple couple = (Couple) iterator.next();
System.out.println(couple.toString());
i++;
}
//判断
Couple c4 = new Couple(28,"EF");
System.out.println(collection.contains(c4));
}
}
特点:有序,有下标,元素可重复
代码实例
public class Demo03 {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Apple");
list.add("XiaoMi");
list.add("HuaWei");
System.out.println("元素个数"+list.size());
System.out.println(list.toString());
for (Object o : list) {
System.out.println(o);
}
for (int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
//listiterator可以向前也可以向后遍历列表
ListIterator listIterator = list.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()+":"+listIterator.next());
}
System.out.println("=====逆序======");
while (listIterator.hasPrevious()){
System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
}
//判断
System.out.println(list.contains("HuaWei"));
System.out.println(list.isEmpty());
//获取位置
System.out.println(list.indexOf("HuaWei"));
}
}
特点:数组结构实现,查询快、增删慢;JDK1.2之后出现的,运行效率快,线程不安全
? 默认容量大小:10 如果没有向集合中添加元素,那么其大小为0;添加任意一个元素后,容量变成10;超过10就会 扩容,每次扩容为前一次的1.5倍(newcapacity=oldcapacity右移一位+newcapacity)
? elementData数组用来存放元素
? size实际元素个数
? add()添加元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
代码实例
public class Couple {
private int age;
private String name;
public Couple(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Couple ["+"name="+this.name+","+"age="+this.age+"]";
}
@Override
public boolean equals(Object obj) {
if (this==obj){
return true;
}
if (obj==null){
return false;
}
if (obj instanceof Couple){
Couple couple = (Couple)obj;
if (this.name.equals(couple.getName())&&this.age==couple.getAge()){
return true;
}
}
return false;
}
}
public class Demo05 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList<>();
Couple c1 = new Couple(16, "AB");
Couple c2 = new Couple(17, "CD");
Couple c3 = new Couple(18, "EF");
arrayList.add(c1);
arrayList.add(c2);
arrayList.add(c3);
System.out.println("the number og the segments is "+arrayList.size());
System.out.println(arrayList);
System.out.println(arrayList.toString());
//arrayList.remove(0);//删除之后,后面的元素会补上来
//arrayList.remove(new Couple(16,"AB"));//方法重写 从地址判断 修改成为内容判断
//System.out.println(arrayList.get(0));
//遍历
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("================列表迭代器顺序==================");
ListIterator listIterator = arrayList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
System.out.println("================列表迭代器逆序==================");
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
//判断
System.out.println(arrayList.contains(new Couple(16,"AB")));
}
}
特点:数组结构实现,查询快,增删慢;JDK1.0出现,运行效率慢,线程安全
代码实例:
public class Demo06 {
public static void main(String[] args) {
//创建集合
Vector vector = new Vector();
vector.add("Apple");
vector.add("Banana");
vector.add("Orange");
vector.add("Strawberry");
System.out.println("元素个数="+vector.size());
//枚举器
Enumeration en = vector.elements();
while (en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
}
特点:链表结构实现,增删快,查询慢;
代码实例
public class Demo07 {
//双向链表
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
Couple c1 = new Couple(1, "A");
Couple c2 = new Couple(2, "B");
Couple c3 = new Couple(3, "C");
linkedList.add(c1);
linkedList.add(c2);
linkedList.add(c3);
System.out.println("元素个数"+linkedList.size());
System.out.println(linkedList);
for (Object o : linkedList) {
System.out.println(o);
}
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
ListIterator listIterator = linkedList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
//获取
System.out.println(linkedList.indexOf(c1));
}
}
Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
常见形式有泛型类、泛型接口、泛型方法
语法:<T,...>T称为类型占位符,表示一种引用类型
好处:
代码实例
//T是类型占位符,表示一种引用类型,如果编写多个,使用逗号隔开
public class MyGeneric <T>{
//使用泛型T
//创建变量,但是不能new一个变量,因为变量的类型不确定,不能实例化
T t;
//添加方法
public void show(T t){
System.out.println(t);
}
//使用泛型作为方法返回值
public T getT(){
return t;
}
}
代码实例
public interface MyInterface <T>{
String name = "Faye";
//不能使用泛型定义静态常量
T server(T t);
}
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String server(String s) {
System.out.println(s);
return null;
}
}
泛型类实现泛型接口
?
public class MyInterfaceImpl2<T> implements MyInterface <T> {
@Override
public T server(T t) {
System.out.println(t);
return null;
}
}
public class MyGenericMethod {
//泛型方法
public void show(){
System.out.println("普通方法");
}
public <T> void show2(T t){
System.out.println(t+"泛型方法");
}
}
public class TestGeneric {
public static void main(String[] args) {
MyGeneric<String> myGeneric = new MyGeneric<>();
myGeneric.t = "hello";
myGeneric.show("hello bitches");
String str = myGeneric.getT();
System.out.println(str);
//泛型只能是引用类型,不同的泛型对象不能相互赋值
MyGeneric<Integer> myGeneric1 = new MyGeneric<>();
myGeneric1.t = 100;
myGeneric1.show(200);
MyInterfaceImpl myInterface = new MyInterfaceImpl();
myInterface.server("????");
MyInterfaceImpl2<String> myInterfaceImpl2 = new MyInterfaceImpl2<>();
myInterfaceImpl2.server("!!!!!!");
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show2("传递的类型不用确定,写啥是啥");
myGenericMethod.show2(11927050);
myGenericMethod.show2(11927050.1314);
}
}
参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:
代码实例
public class Demo01 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("xxx");
arrayList.add("yyy");
for (String s : arrayList) {
System.out.println(s);
}
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
特点:无序、无下标、元素不可重复
方法:全部继承自collection中的方法
代码实例
public class Book implements Comparable<Book>{
private String name;
private int price;
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int hashCode() {
//31是一个质数,减少散列冲突,避免出现hashCode的撞车
//31能够提高执行效率:31*i = (i<<5)-i
int n1 = this.name.hashCode();
int n2 = this.price;
final int prime = 31;
int result = 1;
result = prime*result + price;
result = prime*result + ((name == null)? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this==obj){
return true;
}
if (this == null){
return false;
}
if (this instanceof Book){
Book book = (Book)obj;
if (this.name==book.getName()&&this.price==book.getPrice()){
return true;
}
}
return false;
}
@Override
//先比较姓名 再比较年龄
public int compareTo(Book o) {
int n1 = this.name.compareTo(o.getName());
int n2 = this.price-o.getPrice();
return n1 == 0?n2:n1;
}
}
public class Demo01 {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("《海边的卡夫卡》");
set.add("《世界尽头与冷酷仙境》");
set.add("《且听风吟》");
set.add("《挪威的森林》");
set.add("《刺杀骑士团长》");
set.add("《刺杀骑士团长》");
System.out.println(set.size());
System.out.println(set);
set.remove("《且听风吟》");
//遍历
System.out.println("==================增强for循环==================");
for (String s : set) {
System.out.print(s+" ");
}
System.out.println("");
System.out.println("==================迭代器==================");
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println("");
System.out.println(set.contains("《且听风吟》"));
}
}
基于HashCode实现元素不重复;当存入元素的HashCode相同的时候,会调用equals进行确认,如果结果为true,则拒绝后者的进入
存储结构为哈希表(数组+单向链表)
存储过程:根据hashcode计算保存为止,如果位置为空,则直接保存,如果不为空,则执行第二步
再执行equals方法,若为true,则认为是重复的,否则形成链表
代码实例
public class Demo03 {
public static void main(String[] args) {
HashSet<Book> bookHashSet = new HashSet<>();
Book book1 = new Book("设计中的设计", 100);
Book book2 = new Book("巨人的陨落", 800);
Book book3 = new Book("我们这个世界的羊", 900);
Book book4 = new Book("我们这个世界的羊", 900);
bookHashSet.add(book1);
bookHashSet.add(book2);
bookHashSet.add(book3);
bookHashSet.add(book4);
bookHashSet.add(new Book("我们这个世界的羊", 900));
System.out.println(bookHashSet.size());
//bookHashSet.remove(new Book("我们这个世界的羊", 900));
//System.out.println(bookHashSet.size());
System.out.println(bookHashSet.contains(new Book("我们这个世界的羊", 900)));
}
}
给予排列顺序实现元素不重复
实现了SortedSet接口,对集合元素自动排序;元素对象的类型必须实现Comparable接口,指定排序规则;通过Comparable方法确定是否为重复元素
public class Demo04 {
public static void main(String[] args) {
TreeSet<Book> treeSet = new TreeSet<>();
Book book1 = new Book("设计中的设计", 100);
Book book2 = new Book("巨人的陨落", 800);
Book book3 = new Book("我们这个世界的羊", 900);
Book book4 = new Book("我们这个世界的羊", 900);
treeSet.add(book1);
treeSet.add(book2);
treeSet.add(book3);
treeSet.add(book4);
//元素必须实现comparable接口,compareTo()返回值为0的时候,认为是重复元素
System.out.println(treeSet.size());
}
}
//比较器实现定制比较
public class Demo05 {
public static void main(String[] args) {
//创建集合的时候就制定了比较规则,不用实现接口
TreeSet<Book> treeSet = new TreeSet<>(new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
int n1 = o1.getPrice()-o2.getPrice();
int n2 = o1.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
}
}
练习代码
//使用TreeSet集合来实现字符串按照长度进行排序
//comparator接口
public class Demo06 {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int n1 = o1.length()-o2.length();
int n2 = o1.compareTo(o2);
return n1==0?n2:n1;
}
});
treeSet.add("abcd");
treeSet.add("bcd");
treeSet.add("ebcd");
treeSet.add("abdd");
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
特点:存储一对数据(Key-Value),无序无下标、键不允许重复,值可以重复
代码实例
public class Demo01 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("Cola","5");
map.put("Spine","3.5");
map.put("Soda","4.5");
map.put("Soda","7");
System.out.println(map.size());
System.out.println(map.toString());
//map.remove("Soda");
System.out.println(map.toString());
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.println(s+"===="+map.get(s));
}
for (String s : map.keySet()) {
System.out.println(s+"===="+map.get(s));
}
System.out.println("使用entryset方法");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey()+"==="+entry.getValue());
}
}
}
public class Wechat implements Comparable{
private String username;
private int userage;
public Wechat() {
}
public Wechat(String username, int userage) {
this.username = username;
this.userage = userage;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserage() {
return userage;
}
public void setUserage(int userage) {
this.userage = userage;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime*this.getUsername().hashCode();
result = prime*this.getUserage()+result;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj){
return true;
}
if (obj == null){
return false;
}
if (obj instanceof Wechat){
Wechat wechat = (Wechat)obj;
if (this.userage==wechat.getUserage()&&this.username==wechat.getUsername()){
return true;
}
}
return false;
}
@Override
public int compareTo(Object o) {
Wechat o1 = (Wechat)o;
int n1 = this.username.compareTo(o1.getUsername());
int n2 = this.userage-o1.getUserage();
return n1 == 0?n2:n1;
}
}
JDK1.2版本 线程不安全,运行效率快
1.1 当hashmap刚刚创建的时候,table是null,为了既省空间,当添加第一个元素的时候,table的容量调整为16
1.2 当元素个数大于阈值(16*0.75=12)的时候,会进行扩容,扩容为原来的两倍,目的是减少调整元素的个数
1.3 jdk1.8 当每个链表的长度大于8,并且元素个数大于等于64的时候,会调整为红黑树,目的是提高执行效率
1.4 jdk1.8 当链表长度小于6时,调整成链表
1.5 jdk1.8 链表尾插入
代码实例
public class Demo01 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("Cola","5");
map.put("Spine","3.5");
map.put("Soda","4.5");
map.put("Soda","7");
System.out.println(map.size());
System.out.println(map.toString());
//map.remove("Soda");
System.out.println(map.toString());
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.println(s+"===="+map.get(s));
}
for (String s : map.keySet()) {
System.out.println(s+"===="+map.get(s));
}
System.out.println("使用entryset方法");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey()+"==="+entry.getValue());
}
}
}
public class Demo02 {
public static void main(String[] args) {
HashMap<Wechat, String> hashMap = new HashMap<>();
//刚创建没有添加元素的时候 table = null size = 0 目的是节省空间
Wechat wechat1 = new Wechat("A", 20);
Wechat wechat2 = new Wechat("B", 30);
Wechat wechat3 = new Wechat("C", 40);
Wechat wechat4 = new Wechat("D", 50);
hashMap.put(wechat1,"China");
hashMap.put(wechat2,"America");
hashMap.put(wechat3,"Netherlands");
hashMap.put(wechat4,"England");
hashMap.put(new Wechat("A",20),"China");
System.out.println(hashMap.size());
//entryset方法遍历数组
Set<Map.Entry<Wechat, String>> entrySet = hashMap.entrySet();
for (Map.Entry<Wechat, String> stringEntry : entrySet) {
System.out.println(stringEntry.toString());
}
//keySet方法遍历数组
Set<Wechat> keySet = hashMap.keySet();
for (Wechat wechat : hashMap.keySet()) {
System.out.println(wechat);
}
for (Wechat wechat : keySet) {
System.out.println(wechat);
}
}
}
(目前用的比较少)JDK1.0版本 线程安全 运行效率慢 不允许null作为key或者value
(HashTable的子类)要求key和value都是String,通常用于配置文件的读取
实现了SortedMap接口,可以对key自动排序
代码实例
public class Demo03 {
public static void main(String[] args) {
TreeMap<Wechat, String> treeMap = new TreeMap<>();
Wechat wechat1 = new Wechat("A", 20);
Wechat wechat2 = new Wechat("B", 30);
Wechat wechat3 = new Wechat("C", 40);
Wechat wechat4 = new Wechat("D", 50);
Wechat wechat5 = new Wechat("D", 50);
treeMap.put(wechat1,"China");
treeMap.put(wechat2,"America");
treeMap.put(wechat3,"Netherlands");
treeMap.put(wechat4,"England");
treeMap.put(wechat5,"England");
System.out.println(treeMap.size());
System.out.println("=================keyset=================");
Set<Wechat> keySet = treeMap.keySet();
for (Wechat wechat : keySet) {
System.out.println(wechat+"==="+treeMap.get(wechat));
}
System.out.println("=================entryset=================");
Set<Map.Entry<Wechat, String>> entrySet = treeMap.entrySet();
for (Map.Entry<Wechat, String> stringEntry : entrySet) {
System.out.println(stringEntry);
}
}
}
代码实例
public class Demo04 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(27);
list.add(19);
list.add(69);
list.add(2);
list.add(2);
list.add(4);
list.add(2);
//排序
System.out.println("排序前:"+list.toString());
Collections.sort(list);
System.out.println("排序后:"+list.toString());
//二分法查找 注意二分法的规则以及可能出现的问题
int i1 = Collections.binarySearch(list,12);
int i2 = Collections.binarySearch(list,2);//注意二分查找的规则 这里容易出错
System.out.println(i1);
System.out.println(i2);
//复制 但是复制的操作要求两个集合的大小一致
List<Integer> list2 = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
list2.add(0);
}
Collections.copy(list2,list);
System.out.println(list2);
//逆序
Collections.reverse(list);
System.out.println(list);
//shuffle打乱
Collections.shuffle(list);
System.out.println(list);
//补充:list转成数组
Integer[] array = list.toArray(new Integer[0]);
System.out.println(array.length);
//数组转成list
String[] names = {"Jessica","Linda","Cherry","Sabrina"};
List<String> list1 = Arrays.asList(names);
//受限集合 不能删除或者添加元素
System.out.println(list1);
//如果使用基本类型的话,会使得整个集合中只有一个元素,这个元素就是原来的数组,因此需要使用包装类
Integer[] nums = {20,30,40,60,60};
int[] nums2 = {20,30,40,60,60};
List<Integer> list3 = Arrays.asList(nums);
List<int[]> list4 = Arrays.asList(nums2);
System.out.println(list3.size());
System.out.println(list4.size());
}
}
原文:https://www.cnblogs.com/YabinWang/p/13365882.html