
1.集合主要是两组(单列集合,双列集合)
2.Collection 接口有两个重要的子接口 List Set,他们的实现子类都是单列集合
3.Map 接口的实现子类 是双列集合,存放的K-V
Collection接口和常用方法01:
package HomeWorkD01;
import java.util.ArrayList;
import java.util.List;
public class CollectionDemo {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
list.add("jack");
list.add(10);
list.add(true);
System.out.println(list);
list.remove(new Integer(10));
System.out.println(list);
list.remove("jack");
System.out.println(list);
System.out.println(list.contains("jack"));
System.out.println(list.size());
System.out.println(list.isEmpty());
list.clear();
System.out.println(list);
List list2 = new ArrayList();
list2.add("jack");
list2.add("three countries");
list.addAll(list2);
System.out.println(list);
System.out.println(list.containsAll(list2));
list.removeAll(list2);
System.out.println(list);
}
}
Collection接口遍历元素方式1-iterator(迭代器)
01:
快捷键:itit
all快捷键 ctrl+j
package HomeWorkD01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionIterator {
@SuppressWarnings("all")
public static void main(String[] args) {
Collection col = new ArrayList();
col.add(new Book("three countries","luoguanzhon",10.1));
col.add(new Book("fly knife of li","old long",5.1));
col.add(new Book("red city dream","chaoxuex",34.6));
System.out.println(col);
Iterator iterator = col.iterator();
while(iterator.hasNext())
{
Object next = iterator.next();
System.out.println(next);
}
//itit
// while (iterator.hasNext()) {
// Object next = iterator.next();
//
// }
//重置
iterator = col.iterator();
while(iterator.hasNext())
{
Object next = iterator.next();
System.out.println(next);
}
}
}
class Book
{
private String name;
private String author;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + ''' +
", author='" + author + ''' +
", price=" + price +
'}';
}
}
Collection接口遍历元素方式2-增强for循环
01:
快捷方式 col.for
package HomeWorkD01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionIterator {
@SuppressWarnings("all")
public static void main(String[] args) {
Collection col = new ArrayList();
col.add(new Book("three countries","luoguanzhon",10.1));
col.add(new Book("fly knife of li","old long",5.1));
col.add(new Book("red city dream","chaoxuex",34.6));
//底层还是迭代器
for (Object book : col)
{
System.out.println(book);
}
//也可以在数组使用
int[] nums = {1,2,345,634};
for (int i:nums)
{
System.out.println(i);
}
//col.for 快捷方式
// for (Object o : col) {
//
// }
}
}
class Book
{
private String name;
private String author;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + ''' +
", author='" + author + ''' +
", price=" + price +
'}';
}
}
小练习
01:
package HomeWorkD01;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CollectionArrayListHomeWork01
{
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Dog("small black",3));
list.add(new Dog("big yellow",100));
list.add(new Dog("big strong",8));
for (Object dog : list) {
System.out.println(dog);
}
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object dog = iterator.next();
System.out.println(dog);
}
}
}
class Dog
{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
List接口方法和常用方法
01:
package HomeWorkD01;
import java.util.ArrayList;
import java.util.List;
public class ListDemo01 {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
list.add("tom");
list.add("tom");
list.add("jack");
list.add("bigstrong");
//1.list集合类中元素有序
System.out.println(list);
//2 and 3.list集合中的每个元素都有其对应的顺序索引,即支持索引
//索引从0开始
System.out.println(list.get(3));
//3.
}
}
02:
package HomeWorkD01;
import java.util.ArrayList;
import java.util.List;
public class ListMethod {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
list.add("zsf");
list.add("jby");
//在index 位置插入ele元素
//void add(int index,Object ele)
list.add(1,"hsp");//如果前面没加数字,默认加在最后
System.out.println(list);
//boolean addAll(int index,Collection eles)
//从index位置开始将eles中的所有元素添加进来
List list2 = new ArrayList();
list2.add("jack");
list2.add("tom");
list.addAll(1,list2);
//Object get(int index)
//获取指定index位置的元素
//int indexOf(Object obj)
//返回obj在集合中首次出现的位置
System.out.println(list.indexOf("tom"));
//int lastIndexOf(Object obj)
//返回obj在当前集合中末次出现的位置
System.out.println(list.lastIndexOf("bigstrong"));
//Object remove(int index)
//移除指定index位置的元素,并返回此元素
list.remove(0);
System.out.println(list);
//Object set(int index,Object ele)
//设置指定index位置的元素为ele,相当于是替换
list.set(1,"mali");
//List subList(int fromIndex,int toIndex)
//返回从fromIndex到toIndex位置的子集合 前闭后开
//fromIndex <= subList < toIndex
List list1 = list.subList(0,2);
System.out.println(list1);
}
}
01:
package HomeWorkD01;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListExercise {
@SuppressWarnings("all")
public static void main(String[] args) {
List list = new ArrayList();
for (int i= 0;i<12;i++)
{
list.add("hello"+i);
}
System.out.println(list);
list.add(1,"hspedu");
System.out.println(list);
System.out.println(list.get(4));
list.remove(5);
System.out.println(list);
list.set(6,"three contries");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
}
}
List的三种遍历方式
小练习
01:
package AbstractDemo01;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("all")
public class ListExerciseDemo01 {
public static void main(String[] args) {
List list = new ArrayList();
//List list = new Vector();
//List list = new linkedList();
list.add(new Book01("three countries","luoguanzhon",10.1));
list.add(new Book01("fly knife of li","old long",5.1));
list.add(new Book01("red city dream","chaoxuex",34.6));
list.add(new Book01("west walk dairy","wuce",100));
for (Object o : list) {
System.out.println(o);
}
sort01(list);
for (Object o : list) {
System.out.println(o);
}
}
public static void sort01(List list)
{
int listSize = list.size();
for (int i = 0;i book2.getPrice())
{
list.set(j,book2);
list.set(j+1,book1);
}
}
}
}
}
ArrayList的注意事项
01:
package NanshuoA;
import java.util.ArrayList;
@SuppressWarnings("all")
public class ArrayListDemo01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
//ArrayList 是线程不安全的,没有synchronized
// public boolean add(E e) {
// modCount++;
// add(e, elementData, size);
// return true;
// }
arrayList.add(null);
arrayList.add("jack");
arrayList.add(null);
System.out.println(arrayList);
}
}
ArrayList底层结构和源码分析
01:
分析使用无参构造器,创建和使用ArrayList的源码
package Assign;
import java.util.ArrayList;
@SuppressWarnings("all")
public class ArrayListDemo01Source {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for (int i = 1;i<=10;i++)
{
list.add(i);
}
for (int i = 11;i<=15;i++)
{
list.add(i);
}
list.add(100);
list.add(200);
list.add(null);
for (Object o : list) {
System.out.println(o);
}
}
}
//=================================================================================================
//1.
//创建了一个空的elementData数组 = {}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//add时先装箱
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//装完箱后
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
private Object[] grow() {
return grow(size + 1);
}
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity,
oldCapacity >> 1 );
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
}
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
// assert oldLength >= 0
// assert minGrowth > 0
int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
if (newLength - MAX_ARRAY_LENGTH <= 0) {
return newLength;
}
return hugeLength(oldLength, minGrowth);
}
02:
package Assign;
import java.util.ArrayList;
@SuppressWarnings("all")
public class ArrayListDemo01Source {
public static void main(String[] args) {
ArrayList list = new ArrayList(8);
for (int i = 1;i<=10;i++)
{
list.add(i);
}
for (int i = 11;i<=15;i++)
{
list.add(i);
}
list.add(100);
list.add(200);
list.add(null);
for (Object o : list) {
System.out.println(o);
}
}
}
//=================================================================================================
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
private Object[] grow() {
return grow(size + 1);
}
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity,
oldCapacity >> 1 );
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
}
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
// assert oldLength >= 0
// assert minGrowth > 0
int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
if (newLength - MAX_ARRAY_LENGTH <= 0) {
return newLength;
}
return hugeLength(oldLength, minGrowth);
}
Vector底层结构和源码剖析
01:
package Assign;
import java.util.Vector;
public class VectorDemo01 {
public static void main(String[] args) {
Vector vector = new Vector();
for (int i = 0;i<10;i++)
{
vector.add(i);
}
for (int i = 11;i<=15;i++)
{
vector.add(i);
}
}
}
//===================================================
public Vector() {
this(10);
}
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public synchronized boolean add(E e) {
modCount++;
add(e, elementData, elementCount);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
elementCount = s + 1;
}
private Object[] grow() {
return grow(elementCount + 1);
}
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity,
capacityIncrement > 0 ? capacityIncrement : oldCapacity
);
return elementData = Arrays.copyOf(elementData, newCapacity);
}
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
// assert oldLength >= 0
// assert minGrowth > 0
int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
if (newLength - MAX_ARRAY_LENGTH <= 0) {
return newLength;
}
return hugeLength(oldLength, minGrowth);
}
Vector和ArrayList的比较
linkedList底层结构
01:
package Assign;
import java.util.linkedList;
public class linkedListDemo01 {
public static void main(String[] args) {
Node jack = new Node("jack");
Node tom = new Node("tom");
Node lh = new Node("lh");
jack.next = tom;
tom.next = lh;
lh.pre = tom;
tom.pre = jack;
Node first = jack;
Node last = lh;
while(true)
{
if(first==null)
{
break;
}
System.out.println(first);
first = first.next ;
}
}
}
class Node
{
public Object item;
public Node next;
public Node pre;
public Node(Object name)
{
this.item = name;
}
@Override
public String toString() {
return "Node name = "+item;
}
}
01:
CRUD:
package Assign;
import java.util.linkedList;
@SuppressWarnings("all")
public class linkedListCRUD {
public static void main(String[] args) {
linkedList linkedList = new linkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.remove();//默认删除的是第一个结点
System.out.println(linkedList);
linkedList.set(1,999);
System.out.println(linkedList);
Object o = linkedList.get(1);
System.out.println(o);
for (Object o1 : linkedList) {
System.out.println(o1);
}
for (int i =0 ;i= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
public E remove() {
return removeFirst();
}
public E removeFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
private E unlinkFirst(Node f) {
// assert f == first && f != null;
final E element = f.item;
final Node next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
ArrayList和linkedList比较
Set接口和常用方法
01:
package Assign;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
@SuppressWarnings("all")
public class SetDemo01 {
public static void main(String[] args) {
//取出的顺序虽然不是添加的顺序,但是它是固定的
Set set = new HashSet();
set.add("john");
set.add("lucy");
set.add("jack");
set.add(null);
set.add(null);
set.add("john");
for(int i = 0;i<10;i++)
{
System.out.println(set);
}
System.out.println(set);
//遍历方式
//1.
Iterator iterator = set.iterator();
while(iterator.hasNext())
{
Object obj = iterator.next();
System.out.println(obj);
}
//2.
for (Object o : set) {
System.out.println(o);
}
}
}
Set接口实现类-HashSet
01:
package Assign;
import java.util.HashSet;
@SuppressWarnings("all")
public class HashSetDemo {
public static void main(String[] args) {
HashSet set = new HashSet();
System.out.println(set.add("jack"));//true
System.out.println(set.add("jack"));//false
set.remove("jack");
set = new HashSet();
set.add("lucy");
set.add("lucy");//NO
set.add(new Dog("tom"));
set.add(new Dog("tom"));//YES,这是两个对象
System.out.println(set);
set.add(new String("hsp"));
set.add(new String("hsp"));//NO
System.out.println(set);
}
}
class Dog
{
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + ''' +
'}';
}
}
//============================================================================
public HashSet() {
map = new HashMap<>();
}
HashSet底层机制说明
01:
package Assign;
@SuppressWarnings("all")
public class HashSetStructure {
public static void main(String[] args) {
Node[] nodes = new Node[16];
System.out.println(nodes);
Node john = new Node("john", null);
nodes[2] = john;
Node jack = new Node("jack", null);
john.next = jack;
Node rose = new Node("Rose", null);
jack.next = rose;
Node lucy = new Node("lucy",null);
nodes[3] = lucy;
System.out.println(nodes);
}
}
class Node
{
Object item;
Node next;
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}
01:
package BigDemo;
import java.util.HashSet;
@SuppressWarnings("all")
public class HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("java");
hashSet.add("php");
hashSet.add("java");
System.out.println(hashSet);
}
}
//==================================================================================
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;//(static) PRESENT = new object();
}
private static final Object PRESENT = new Object();
//得到key对应的hash值 算法 h = key.hashCode()*(h>>>16)
public V put(K key, V value) {//key = "java" value = PRESENT 共享
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
//if 语句表示如果当前table 是null,或者大小 = 0
//就是第一次扩容,到16个空间.
if ((tab = table) == null || (n = tab.length) == 0)//transient Node[] table;
n = (tab = resize()).length;
//(1)根据key,得到hash 去计算该key应该存放到table表的哪个索引位置
//并把这个位置的对象,赋给p
//(2)判断p是否为null
//如果p为null,表示还没存放元素,就创建一个Node(key = "java",value = PRESENT)
//就放在该位置 tab[i] = newNode(hash,key,value,null)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
//准备加入的key和p指向的Node结点的key是同一个对象
//p指向的Node结点的key的key的equals()和准备加入的key比较后相同就不能加入
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//再判断p是不是一颗红黑树
//如果是一颗红黑树,就调用putTreeval,来进行添加
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeval(this, tab, hash, key, value);
else {
//依次和该链表中的每一个元素比较后,都不相同,则加入到该链表的最后
//注意在把元素添加到链表后,立即判断该链表是否已经到达8个结点
//就调用treeifyBin() 对当前这个链表进行树化(转成红黑树)
//注意,在转成红黑树时,要进行判断,如果该table数组的大小小于64
// if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//64
// resize();
//先table扩容
//只有上面条件不成立后,才会转为红黑树
//依次和该链表的每一个元素比较过程中,如果有相同情况,就直接break
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
// final void treeifyBin(Node[] tab, int hash) {
// int n, index; HashMap.Node e;
// if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//64
// resize();
// else if ((e = tab[index = (n - 1) & hash]) != null) {
// HashMap.TreeNode hd = null, tl = null;
// do {
// HashMap.TreeNode p = replacementTreeNode(e, null);
// if (tl == null)
// hd = p;
// else {
// p.prev = tl;
// tl.next = p;
// }
// tl = p;
// } while ((e = e.next) != null);
// if ((tab[index] = hd) != null)
// hd.treeify(tab);
// }
// }
//
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
final Node[] resize() {
Node[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode)e).split(this, newTab, j, oldCap);
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
01:
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
static final float DEFAULT_LOAD_FACTOR = 0.75f;
02:
package BigDemo;
import java.util.HashMap;
import java.util.HashSet;
@SuppressWarnings("all")
public class HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
for (int i = 1;i<=12;i++)
{
hashSet.add(new A(i));
}
for (int i = 1;i<=100;i++)
{
hashSet.add(i);
}
}
}
class A
{
private int n;
public A(int n)
{
this.n = n;
}
@Override
public int hashCode() {
return 100;
}
}
03:
package BigDemo;
import java.util.HashMap;
import java.util.HashSet;
@SuppressWarnings("all")
public class HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
//size 就是我们每加入一个结点Node(k,v,h,next)
for (int i = 1;i<=7;i++)
{
hashSet.add(new A(i));//在table的某一条链表中添加了7个A对象
}
for (int i = 1;i<=7;i++)
{
hashSet.add(new B(i));//在table的另外一条链表上添加了7个B对象
}
}
}
class B
{
private int n;
public B(int n) {
this.n = n;
}
@Override
public int hashCode() {
return 200;
}
}
class A
{
private int n;
public A(int n)
{
this.n = n;
}
@Override
public int hashCode() {
return 100;
}
}
小练习
01:
package HashSetDemo01Work;
import java.util.HashSet;
@SuppressWarnings("all")
public class HashSetDemo01 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("milan",18));
hashSet.add(new Employee("jock",23));
hashSet.add(new Employee("milan",18));
System.out.println(hashSet);
}
}
class Employee
{
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
//先计算hashCode()再计算equals()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (age != employee.age) return false;
return name != null ? name.equals(employee.name) : employee.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
01:
package HashSetDemo01Work;
import java.util.HashSet;
public class HashSetDemoWork01 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
MyDate myDate01 = new MyDate("2001", "2", "3");
hashSet.add(new Employee01("tom",78899,myDate01));
MyDate myDate02 = new MyDate("2001","2","3");
hashSet.add(new Employee01("tom",78899,myDate02));
System.out.println(hashSet);
}
}
class Employee01
{
private String name;
private double sal;
MyDate birthday;
public Employee01(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Employee01{" +
"name='" + name + ''' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee01 that = (Employee01) o;
if (Double.compare(that.sal, sal) != 0) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return birthday != null ? birthday.equals(that.birthday) : that.birthday == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = name != null ? name.hashCode() : 0;
temp = Double.doubleToLongBits(sal);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
return result;
}
}
class MyDate
{
private String year;
private String month;
private String day;
public MyDate(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyDate myDate = (MyDate) o;
if (year != null ? !year.equals(myDate.year) : myDate.year != null) return false;
if (month != null ? !month.equals(myDate.month) : myDate.month != null) return false;
return day != null ? day.equals(myDate.day) : myDate.day == null;
}
@Override
public int hashCode() {
int result = year != null ? year.hashCode() : 0;
result = 31 * result + (month != null ? month.hashCode() : 0);
result = 31 * result + (day != null ? day.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "MyDate{" +
"year='" + year + ''' +
", month='" + month + ''' +
", day='" + day + ''' +
'}';
}
}
Set接口实现类-linkedHashSet
01:
- linkedHashSet 加入顺序和取出元素/数据的顺序一致
- linkedHashSet 底层维护的是一个linkedHashMap(是HashMap的子类)
- linkedHashSet 底层结构(数组+双向链表)
- 添加第一次时,直接将数组table扩容到16,存放的结点类型是linkedHashMap$Entry
- 数组是HashMap N o d e [ ] 存 放 的 元 素 / 数 据 是 L i n k e d H a s h M a p Node[] 存放的元素/数据是 linkedHashMap Node[]存放的元素/数据是LinkedHashMapEntry类型
package linkedHashSetSource;
import java.util.linkedHashSet;
@SuppressWarnings("all")
public class linkedHashSetSource {
public static void main(String[] args) {
linkedHashSet set = new linkedHashSet();
set.add(new String("AA"));
set.add(456);
set.add(456);
set.add(new Customer("liu",1001));
set.add(123);
set.add("HSP");
//有序
System.out.println(set);
}
}
class Customer
{
private String name;
private double no;
public Customer(String name, double no) {
this.name = name;
this.no = no;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + ''' +
", no=" + no +
'}';
}
}
小练习
01:
package linkedHashSetSource;
import java.util.linkedHashSet;
@SuppressWarnings("all")
public class linkedHashSetExercise01 {
public static void main(String[] args) {
linkedHashSet set = new linkedHashSet();
set.add(new Car("baoma",12321));
set.add(new Car("baoma",12321));
set.add(new Car("flll",131231));
set.add(new Car("asdsa",13124));
System.out.println(set);
}
}
class Car
{
private String name;
private double price;
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + ''' +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
if (Double.compare(car.price, price) != 0) return false;
return name != null ? name.equals(car.name) : car.name == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = name != null ? name.hashCode() : 0;
temp = Double.doubleToLongBits(price);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
Map接口和常用方法
01:
-
Map与Collection并列存在,用于保存具有映射关系的数据:Key-Value(双列元素)
-
Map中的key和value可以是任何引用类型的数据,会封装到HashMap$Node对象中
-
Map中的key不允许重复,原因和HashSet一样
-
Map中的value可以重复
-
Map的key可以为null,value也可以为null,注意key为null,只能有一个,value为null,可以多个
-
常用String类作为Map的key
-
key和Value之间存在单向一对一关系,即通过指定的key总能找到对应的value
package MapDemo01;
import java.util.HashMap;
@SuppressWarnings("all")
public class MapDemo {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("no1","hsp");
map.put("no2","jack");
map.put("no1","asdas");//当有相同的K,就等价于替换
map.put("no3","zsf");
map.put(null,null);
map.put(null,"abc");//替换
map.put("no4",null);
map.put("no5",null);
System.out.println(map.get("no1"));
System.out.println(map);
}
}
Map接口的特点
01:
package MapDemo01;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("all")
public class MapDemo {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("no1","hsp");
map.put("no2","jack");
System.out.println(map);
//1.K-V 最后是HashMap$Node node = newNode(hash,key,value,null)
//2.K-V 为了方便程序员的遍历,还会创建EntrySet 集合,该集合存放的元素的类型 Entry,而一个Entry
//对象就有K,V EntrySet> 即: transient Set> entrySet
//3.entrySet中,定义的类型是Map.Entry,但是实际上存放的还是HashMap$Node
//4.当把HashMap$Node对象存放到entrySet 就方便我们的遍历,因为Map.Entry提供了重要的方法
Set set = map.entrySet();//class java.util.HashMap$EntrySet
System.out.println(set.getClass());
for (Object obj : set) {
System.out.println(obj.getClass());//class java.util.HashMap$Node
//为了从HashMap$Node 取出k-v
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry);
System.out.println(entry.getKey()+" "+entry.getValue());
}
Set set1 = map.keySet();
System.out.println(set1.getClass());
Collection values = map.values();
System.out.println(values.getClass());
//class java.util.HashMap$KeySet
//class java.util.HashMap$Values
}
}
//==================================================
Node newNode(int hash, K key, V value, Node next) {
return new Node<>(hash, key, value, next);
}
transient Set> entrySet;
final class EntrySet extends AbstractSet> {//...
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//hhhhhhhhhhhhhhhhhhhhhhhhhhhh
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeval(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//Entryk就是set,v就是Collection,然后Entry是一个数据类型,EntrySet是一个集合,Entry就会作为一个数据放进这个集合里面
static class Node implements Map.Entry {
final int hash;
final K key;
V value;
Node next;
Node(int hash, K key, V value, Node next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry,?> e = (Map.Entry,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
interface Entry {
K getKey();
V getValue();
V setValue(V value);
Map体系的继承图
Map体系图的说明
01:
package EnumWork;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("all")
public class MapMethod {
public static void main(String[] args) {
Map map = new HashMap();
//无序的
map.put("dc",new Book("",100));
map.put("adas","dasda");
map.put("dasd",null);
map.put(null,"dasdas");
System.out.println(map);
//根据KEY删除映射关系
map.remove(null);
//get 根据KEY获取值
Object adas = map.get("adas");
//size获取元素个数
System.out.println(map.size());
//isEmpty 判断是否为空
System.out.println(map.isEmpty());
//clear 清空
map.clear();
//containsKey : 查找KEY是否存在
System.out.println(map.containsKey("hsp"));
}
}
class Book
{
private String name;
private int age;
public Book(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
Map接口遍历方法
01:
package EnumWork;
import java.util.*;
@SuppressWarnings("all")
public class MapMethod {
public static void main(String[] args) {
Map map = new HashMap();
//无序的
map.put("dc",new Book("",100));
map.put("adas","dasda");
map.put("dasd",null);
map.put(null,"dasdas");
//1.
Set keySet = map.keySet();
for (Object key:keySet)
{
System.out.println(key+" "+map.get(key));
}
//2.
Iterator iterator = keySet.iterator();
while(iterator.hasNext())
{
Object key = iterator.next();
System.out.println(key+" "+map.get(key));
}
Collection values = map.values();
//1.
for (Object v:values)
{
System.out.println(v);
}
//2.
Iterator iterator1 = values.iterator();
while(iterator1.hasNext())
{
Object value= iterator1.next();
System.out.println(value);
}
//1.
Set entrySet = map.entrySet();//EntrySet>
for (Object entry:entrySet)
{
//将entry -> Map.Entry
Map.Entry m = (Map.Entry) entry;
System.out.println(m.getKey()+" "+m.getValue());
}
//2.
Iterator iterator3 = entrySet.iterator();
while(iterator3.hasNext())
{
Object next= iterator3.next();
// System.out.println(next.getClass());//HashMap$Node -> Map.Entry(getKey,getValue)
//向下转型 Map.Entry
Map.Entry m = (Map.Entry) next;
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
class Book
{
private String name;
private int age;
public Book(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
小练习
01:
package EnumWork;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("all")
public class HashMapDemoWork01 {
public static void main(String[] args) {
Map map = new HashMap();
map.put(1,new Emp("jack",300000,1));
map.put(2,new Emp("tom",1000,2));
map.put(3,new Emp("asd",2314,3));
Set keySet = map.keySet();
for (Object key:keySet)
{
Emp emp = (Emp)map.get(key);
if (emp.getSal() > 18000)
{
System.out.println(emp);
}
}
Set entrySet = map.entrySet();
Iterator iterator = entrySet.iterator();
while(iterator.hasNext())
{
Map.Entry entry = (Map.Entry)iterator.next();
Emp emp = (Emp) entry.getValue();
if (emp.getSal() > 18000)
{
System.out.println(emp);
}
}
}
}
class Emp
{
private String name;
private double sal;
private int id;
public Emp(String name, double sal, int id) {
this.name = name;
this.sal = sal;
this.id = id;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + ''' +
", sal=" + sal +
", id=" + id +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
HashMap小结
HashMap底层机制及源码剖析
Map接口实现类-Hashtable
01:
package BooleanTest;
import java.util.Hashtable;
@SuppressWarnings("all")
public class HashTableExercise {
public static void main(String[] args) {
//1.底层有数组,Hashtable$Entry[] 初始大小为11
//2.临界值 threshold 8 = 11*0.75
//3.扩容:按照自己的扩容机制来进行即可
Hashtable hashtable = new Hashtable();
hashtable.put("lucy",100);
hashtable.put("lucy",25235);
//hashtable.put(null,1312);//Error
//hashtable.put("dadas",null);//Error
}
}
//=================================================================================
public Hashtable() {
this(11, 0.75f);
}
private static class Entry implements Map.Entry {
final int hash;
final K key;
V value;
Entry next;
//.........
}
01:
package BooleanTest;
import java.util.Hashtable;
@SuppressWarnings("all")
public class HashTableExercise {
public static void main(String[] args) {
//1.底层有数组,Hashtable$Entry[] 初始大小为11
//2.临界值 threshold 8 = 11*0.75
//3.扩容:按照自己的扩容机制来进行即可
//4.执行方法 appEntry(hash,key,value,index) 添加K-V 封装到Entry
//5.当if(count >= threshold)满足时,就进行扩容
//按照int newCapacity = (oldCapacity << 1)+1 的大小扩容
Hashtable hashtable = new Hashtable();
hashtable.put("lucy",100);
hashtable.put("lucy",25235);
hashtable.put("hello1",31);
hashtable.put("hello22",31231);
hashtable.put("hello3",3321);
hashtable.put("hello14",31441);
hashtable.put("hello51",341);
hashtable.put("hello61",37561);
hashtable.put("hello71",38671);
hashtable.put("hello81",34561);
hashtable.put("hello91",371);
}
}
//====================================================================================
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry entry = (Entry)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
private void addEntry(int hash, K key, V value, int index) {
Entry,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry e = (Entry) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
modCount++;
}
protected void rehash() {
int oldCapacity = table.length;
Entry,?>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry,?>[] newMap = new Entry,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry old = (Entry)oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry)newMap[index];
newMap[index] = e;
}
}
}
Hashtable和HashMap的对比
Map接口实现类-Properties
01:
package CharTest;
import java.util.Properties;
@SuppressWarnings("all")
public class PropertieisDemo01 {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("jack",100);
properties.put("tom",312);
//properties.put(null,131);//ERROR
//properties.put("1321",null);//ERROR
properties.put("lic",99);
//无序
System.out.println(properties);
System.out.println(properties.get("jack"));
properties.remove("lic");
System.out.println(properties);
properties.put("tom",4312421);//修改
}
}
Collections工具类
01:
package CharTest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@SuppressWarnings("all")
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("tom");
list.add("jack");
list.add("tom");
list.add("milan");
System.out.println(list);
//反转
Collections.reverse((list));
System.out.println(list);
//随机排序
Collections.shuffle(list);
System.out.println(list);
//按升序排序
Collections.sort(list);
System.out.println(list);
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof String) {
return ((String) o1).length() - ((String) o2).length();
}else return 0;
}
});
System.out.println(list);
//交换下标为0和1的元素的位置
Collections.swap(list,0,1);
System.out.println(list);
//返回最大值
System.out.println(Collections.max(list));
System.out.println(Collections.max(list,new Comparator()
{
@Override
public int compare(Object o1, Object o2) {
return ((String)o1).length()-((String)o2).length();
}
}));
//返回最小值
System.out.println(Collections.min(list));
//返回指定元素出现的次数
System.out.println(Collections.frequency(list,"tom"));
//void copy(List dest,List src):将src中的内容复制到dest中
//为完成一个完整赋值,我们需要先给dest赋值,大小和list.size()一样
ArrayList list1 = new ArrayList();
for (int i = 0;i
总结-开发中如何选择集合实现类(记住)
还没更完,有时间再更,有几个集合没写,比如TreeSet,TreeMap等
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)