定義
1.集合是用來存儲數(shù)據(jù)的,也是數(shù)據(jù)的一種容器,集合只能去存儲對象,每個對象就是集合中的一個元素。
數(shù)組和集合之間的區(qū)別?
數(shù)組
1.數(shù)組長度固定
2.數(shù)組只能存儲同一種數(shù)據(jù)類型 , 但是數(shù)組是能存基本數(shù)據(jù)類型和引用數(shù)據(jù)類型的
引用數(shù)據(jù)類型:引用(對象引用的地址)
引用數(shù)據(jù)類型有哪些:數(shù)組,類,接口
集合
3.集合的長度不固定,它不用聲明具體的長度,集合是可以自動擴容的 ,集合只能去存儲對象。
集合可以存儲多種數(shù)據(jù)類型 (注意:真實項目中,一般集合中通常只存同一種數(shù)據(jù)類型)
思考:集合中是否能存儲數(shù)字? 集合中存儲的數(shù)字是int 類型的包裝類。
集合的語法
集合是存放在Java.util包下
共同的接口:Collection接口
map集合:
也可以去存放數(shù)據(jù),map集合存放數(shù)據(jù)的方式是通過(鍵值對)的方式來存儲的
鍵 Key 存放的一個地址
值value <key , value>
可以通過鍵 key快速的 查找到 具體的 value值
將123存入map 以鍵值對的方式存儲

list集合中ArrayList語法
public class Test {
public static void main(String[] args) {
//list集合中 ArrayList的語法
//創(chuàng)建集合 面向接口
List list = new ArrayList();
}
}
往集合中加數(shù)據(jù)
public class Test {
public static void main(String[] args) {
//list集合中 ArrayList的語法
//創(chuàng)建集合 面向接口
List list = new ArrayList();
list.add("haha");
list.add(123);
list.add(12.5);
System.out.println(list);
}
}
注意:如果list集合 在不加泛型的情況下,默認的屬性為object類型
泛型:如果一個集合 添加泛型 此集合就只能存儲 泛型中的數(shù)據(jù)類型
泛型語法:list<數(shù)據(jù)類型>
加了泛型的集合
public class Test {
public static void main(String[] args) {
List<Integer> list2 = new ArrayList<>();
list2.add(123);
list2.add(369);
list2.add(999);
list2.add(58);
//將制定元素插入制定位置
list2.add(2 , 56);
System.out.println(list2);
}
}
上述代碼如下圖

集合的長度是.size
集合中add()方法和addall()方法的區(qū)別:
add:向集合中插入一個元素 , 如果此元素有多條數(shù)據(jù),那么這些數(shù)據(jù)共享一個下標
addall : 先將對象中的數(shù)據(jù)一一拿出分別存入集合當中(傳入的對象中,有多少個元素就占多少個下標)
注意:addall(集合對象)的參數(shù)為集合對象
- 例題,運行查看結果
import java.util.List;
/**
* Created by ttc on 2018/6/1.
*/
public class Test {
public static void main(String[] args) {
//list集合中 ArrayList的語法
//創(chuàng)建集合 面向接口
List list = new ArrayList();
list.add("haha");
list.add(123);
list.add(12.5);
System.out.println(list);
List list2 = new ArrayList<>();
list2.add(123);
list2.add(369);
list2.add(999);
list2.add(58);
list2.add(2 , 56);
System.out.println(list2);
list2.addAll(list);
System.out.println(list2);
list2.add(list);
System.out.println(list2);
}
//面向實現(xiàn)類
// ArrayList list2 = new ArrayList();
}
list。contains(123)如果此列中包含指定元素,則返回true
此方法的參數(shù)為object類型,對象和具體的數(shù)據(jù)都可以傳入
集合的遍歷
用什么方式遍歷集合,為什么?
for循環(huán),需要知道 集合的長度
我們可以求出集合的長度,所以用For循環(huán)
//list2.get 訪問集合中 具體元素索引值
for (int i = 0 ; i < list2.size();i++)
{
System.out.println(list2.get(i));
}
}
思考,Arraylist 自動擴容 是如何實現(xiàn)的 ?
list 集合 底層還是用數(shù)組實現(xiàn)的 , 那么數(shù)組不是定長的么?
首先:當我們創(chuàng)建一個數(shù)組時,其長度 是我們手動設置的 , 但是 在list集合中,在創(chuàng)建一個集合時:默認開辟一個長度為10 的一個集合空間,如果此空間存放滿了, jvm會 在原來 空間基礎上*1.5倍,進行自動擴容。
list集合的 特點:list 是一種 線性集合。
linkedlist : 底層也是用數(shù)組來實現(xiàn)的, 它的實現(xiàn)方式 是通過 鏈表 來實現(xiàn)的
Arraylist 特點:訪問快 , 但是插入刪除慢
linkedlist 特點:訪問慢, 但是插入刪除快 , 用法與Arraylist一致
linkedlist語法
List list3 = new LinkedList();
特點:list集合是 有序可重復的集合
可重復:可以有重復的數(shù)據(jù)
序:按照存入的順序進行排序
set集合
1.set集合是 無序 不重復 集合
無序:不按照存入順序排序
不重復:set集合中 不允許有重復的數(shù)據(jù)
Map接口
建立國家英文簡稱和中文全名間的鍵值映射,并通過key對value進行操作,應該如何實現(xiàn)數(shù)據(jù)的存儲和操作呢?

Map接口專門處理鍵值映射數(shù)據(jù)的存儲,可以根據(jù)鍵實現(xiàn)對值的操作
最常用的實現(xiàn)類是HashMap

Map接口常用方法

遍歷List和Map
for(元素類型t 元素變量x : 數(shù)組或集合對象){
引用了x的java語句
}
練習
1.第一題 (Map)利用Map,完成下面的功能:
從命令行讀入一個字符串,表示一個年份,輸出該年的世界杯冠軍是哪支球隊。如果該 年沒有舉辦世界杯,則輸出:沒有舉辦世界杯。
歷屆世界杯冠軍
屆數(shù) 舉辦年份 舉辦地點 冠軍
第一屆 1930年 烏拉圭 烏拉圭
第二屆 1934年 意大利 意大利
第三屆 1938年 法國 意大利
第四屆 1950年 巴西 烏拉圭
第五屆 1954年 瑞士 西德
第六屆 1958年 瑞典 巴西
第七屆 1962年 智利 巴西
第八屆 1966年 英格蘭 英格蘭
第九屆 1970年 墨西哥 巴西
第十屆 1974年 前西德 西德
第十一屆 1978年 阿根廷 阿根廷
第十二屆 1982年 西班牙 意大利
第十三屆 1986年 墨西哥 阿根廷
第十四屆 1990年 意大利 西德
第十五屆 1994年 美國 巴西
第十六屆 1998年 法國 法國
第十七屆 2002年 韓日 巴西
第十八屆 2006年 德國 意大利
第十九屆 2010年 南非 西班牙
第二十屆 2014年 巴西 德國
(Map)在原有世界杯Map 的基礎上,增加如下功能: 讀入一支球隊的名字,輸出該球隊奪冠的年份列表。 例如,讀入“巴西”,應當輸出 1958 1962 1970 1994 2002 讀入“荷蘭”,應當輸出 沒有獲得過世界杯


package com.company;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Created by ttc on 2018/1/10.
*/
public class WorldCupDemo {
public static void main(String[] args) {
Map<Integer,String> year2country = new HashMap<>();
year2country.put(1930,"烏拉圭");
year2country.put(1934,"意大利");
year2country.put(1938,"意大利");
year2country.put(1950,"烏拉圭");
year2country.put(1954,"西德");
year2country.put(1958,"巴西");
year2country.put(1962,"巴西");
year2country.put(1966,"英格蘭");
year2country.put(1970,"巴西");
year2country.put(1974,"西德");
year2country.put(1978,"阿根廷");
year2country.put(1982,"意大利");
year2country.put(1986,"阿根廷");
year2country.put(1990,"西德");
year2country.put(1994,"巴西");
year2country.put(1998,"法國");
year2country.put(2002,"巴西");
year2country.put(2006,"意大利");
year2country.put(2010,"西班牙");
year2country.put(2014,"德國");
Scanner scanner = new Scanner(System.in);
System.out.println("輸入年份");
int year = scanner.nextInt();
if(year2country.containsKey(year))
{
System.out.println("該年的冠軍是" + year2country.get(year));
}
else
{
System.out.println("該年沒有舉行世界杯");
}
System.out.println("請輸入國家名");
String countryName = scanner.next();
//遍歷map集合,考察每一個元素的value,是否和用戶輸入的國家一樣
//如果一樣,輸出和value對應key
boolean bFind = false;//沒有在map中找到該國家
for(Integer key : year2country.keySet())
{
String country = year2country.get(key);
if(country.equals(countryName))
{
System.out.println(key);
bFind = true;
}
}
//如果前面map遍歷一遍之后,bFind的值依然是false,說明map集合中不存在用戶輸入的國家名
if(bFind == false)
{
System.out.println("該國家沒有獲得過世界杯冠軍");
}
}
}
2.第二題 已知有十六支男子足球隊參加2008 北京奧運會。寫一個程序,把這16 支球隊隨機分為4 個組。采用List集合和隨機數(shù)
2008 北京奧運會男足參賽國家:
科特迪瓦,阿根廷,澳大利亞,塞爾維亞,荷蘭,尼日利亞,日本,美國,中國,新西蘭,巴西,比利時,韓國,喀麥隆,洪都拉斯,意大利
提示:分配一個,刪除一個

public class Maintemp {
public static void main(String[] args) {
String str = "科特迪瓦,阿根廷,澳大利亞,塞爾維亞,荷蘭,尼日利亞,日本,美國,中國," +
"新西蘭,巴西,比利時,韓國,喀麥隆,洪都拉斯,意大利";
String[] str1 = str.split(",");
System.out.println(str1.length);
List<String> list2team = new ArrayList<>();
for (int i = 0 ;i <str1.length;i++)
{
list2team.add(str1[i]) ;
}
System.out.println(list2team);
List<String> list2teamMin = new ArrayList<>();
Random random = new Random();
for (int j = 0 ; j < 4 ;j++)
{
for (int i = 0; i < 4; i++)
{
int suiji = random.nextInt(list2team.size());
list2teamMin.add(list2team.get(suiji));
list2team.remove(list2team.get(suiji));
}
System.out.println(list2teamMin);
list2teamMin.clear(); //清空小集合中的數(shù)據(jù),再次添加一組新的。
}
}
}
3.第三題 有如下Student 對象,
private String name;
private int age;
private int score;
private String classNum;
其中,classNum 表示學生的班號,例如“class05”。 有如下
List List list = new ArrayList();
list.add(new Student(“Tom”, 18, 100, “class05”));
list.add(new Student(“Jerry”, 22, 70, “class04”));
list.add(new Student(“Owen”, 25, 90, “class05”));
list.add(new Student(“Jim”, 30,80 , “class05”));
list.add(new Student(“Steve”, 28, 66, “class06”));
list.add(new Student(“Kevin”, 24, 100, “class04”));
在這個list 的基礎上,完成下列要求:
1) 計算所有學生的平均年齡
2) 計算各個班級的平均分

package com.maptest;
import jdk.internal.util.xml.impl.Input;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ttc on 2018/6/4.
*/
public class TestStudents {
public static void main(String[] args) {
List<Student> list = new ArrayList();
list.add(new Student("Tom", 18, 100, "class05"));
list.add(new Student("Jerry", 22, 70, "class04"));
list.add(new Student("Owen", 25, 90, "class05"));
list.add(new Student("Jim", 30,80 , "class05"));
list.add(new Student("Steve", 28, 66, "class06"));
list.add(new Student("Kevin", 24, 100, "class04"));
//每個班級的學生成績列表
Map<String,List<Integer>> mapClass2Scores = new HashMap<>();
// [class04:(70,100);class05:(100,90,80);class06:(66)];
for(Student student : list)
{
if(mapClass2Scores.containsKey(student.getClassNum()))
{
//拿到當前班級的學生成績列表對象
List<Integer> lst = mapClass2Scores.get(student.getClassNum());
lst.add(student.getScore());
}
else//該學生所在班級,第一次加入到map中
{
List<Integer> lst = new ArrayList<>();
lst.add(student.getScore());
mapClass2Scores.put(student.getClassNum(),lst);
}
}
for(Map.Entry entry : mapClass2Scores.entrySet())
{
System.out.println("班級:" + entry.getKey());
List<Integer> listScores = (List<Integer>)entry.getValue();
int sum = 0;
for(Integer score : listScores)
{
sum += score;
}
System.out.println(sum/listScores.size());
}
int age_sum = 0;
for(Student student : list)
{
age_sum += student.getAge();
}
System.out.println(age_sum/list.size());
}
}
學生類
package com.maptest;
/**
* Created by ttc on 2018/6/4.
*/
public class Student {
private String name;
private int age;
private int score;
private String classNum;
public Student(String name, int age, int score, String classNum) {
this.name = name;
this.age = age;
this.score = score;
this.classNum = classNum;
}
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;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getClassNum() {
return classNum;
}
public void setClassNum(String classNum) {
this.classNum = classNum;
}
}
5.第五題(Map)設計Account 對象如下:
private long id;
private double balance;
private String password;
要求完善設計,使得該Account 對象能夠自動分配id。 給定一個List 如下:
List list = new ArrayList();
list.add(new Account(10.00, “1234”));
list.add(new Account(15.00, “5678”));
list.add(new Account(0, “1010”));
要求把List 中的內容放到一個Map 中,該Map 的鍵為id,值為相應的Account 對象。 最后遍歷這個Map,打印所有Account 對象的id 和余額。

package com.company;
import java.util.UUID;
/**
* Created by ttc on 2018/1/11.
*/
public class Account {
private String sid;//使用UUID來生成
private double balance;
private String password;
public Account(double balance, String password)
{
this.balance = balance;
this.password = password;
//自動分配賬號
this.sid = UUID.randomUUID().toString();
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.company;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ttc on 2018/1/11.
*/
public class TestAccount {
public static void main(String[] args) {
List<Account> accountList = new ArrayList<>();
accountList.add(new Account(100,"123"));
accountList.add(new Account(10,"456"));
accountList.add(new Account(80,"111"));
//將數(shù)據(jù)轉移到map結構
Map<String,Account> accountMap = new HashMap<String,Account>();
for(Account account : accountList)
{
accountMap.put(account.getSid(),account);
}
for(Map.Entry<String,Account> entry: accountMap.entrySet())
{
System.out.println(entry.getKey() + " " + entry.getValue().getSid());
}
}
}
Account的id自增長版本
package com.company;
import java.util.UUID;
/**
* Created by ttc on 2018/1/11.
*/
public class Account {
// private String sid;//使用UUID來生成
private long sid;
private double balance;
private String password;
private static int object_count = 0;
public Account(double balance, String password)
{
this.balance = balance;
this.password = password;
//自動分配賬號
//this.sid = UUID.randomUUID().toString();
//先獲得當前本類已經(jīng)創(chuàng)建了多少個對象
this.sid = Account.object_count + 1;
Account.object_count++;
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public static void main(String[] args) {
List<Account> accountList = new ArrayList<>();
accountList.add(new Account(100,"123"));//A
accountList.add(new Account(10,"456"));//B
accountList.add(new Account(80,"111"));
accountList.add(new Account(330,"333"));
//將數(shù)據(jù)轉移到map結構
Map<Long,Account> accountMap = new HashMap<Long,Account>();
for(Account account : accountList)
{
accountMap.put(account.getSid(),account);
}
for(Map.Entry<Long,Account> entry: accountMap.entrySet())
{
System.out.println(entry.getKey() + " " + entry.getValue().getSid());
}
}
6.第六題(List)已知有一個Worker 類如下:
public class Worker
{ private int age;
private String name;
private double salary;
public Worker (){}
public Worker (String name, int age, double salary)
{ this.name = name;
this.age = age;
this.salary = salary; }
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; }
public double getSalary(){ return salary; }
public void setSalary(double salary){ this.salary = salary; }
public void work(){
System.out.println(name + “ work”); } }
完成下面的要求
創(chuàng)建一個List,在List 中增加三個工人,基本信息如下:
姓名 年齡 工資
zhang3 18 3000
li4 25 3500
wang5 22 3200
在li4 之前插入一個工人,信息為:姓名:zhao6,年齡:24,工資3300
刪除wang5 的信息
利用for 循環(huán)遍歷,打印List 中所有工人的信息
利用迭代遍歷,對List 中所有的工人調用work 方法。

List<Worker> workerList = new ArrayList<>();
workerList.add(new Worker("zhangsan",12,2445));
workerList.add(new Worker("lisi",32,5445));
workerList.add(new Worker("wangwu",22,7445));
Worker worker = new Worker("zhaoliu",33,5645);
workerList.add(1,worker);
workerList.remove(3);
for(int i = 0; i < workerList.size();i++)
{
System.out.println(workerList.get(i));
}
for(Worker worker1 : workerList){
worker1.work();
}
經(jīng)典練習
一篇英文文章,單詞間用空格分割,統(tǒng)計出現(xiàn)了哪些單詞,以及每個單詞出現(xiàn)的次數(shù)。
package com.test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ttc on 2018/6/1.
*/
public class WordCount {
public static void main(String[] args) {
// 程序 = 數(shù)據(jù)結構 + 算法
String strTemp = "this is a dog that is a desk long long ago there is a girl";
String[] strArrays = strTemp.split(" ");
System.out.println(Arrays.toString(strArrays));
Map<String,Integer> map = new HashMap<>();
//把單詞在字符串數(shù)組中保存轉換為在map中保存
for(String strWord : strArrays)
{
//去map中考察,看map的key的集合中是否包含該單詞
//如果不包含,往map中添加一個元素,key是單詞,值是1
if(!map.containsKey(strWord))
{
map.put(strWord,1);
}
//如果包含,從map中通過該key取到對應的值(該單詞之前已經(jīng)出現(xiàn)過的次數(shù))
//把這個值加1,在存回去
else
{
Integer count = map.get(strWord);
count++;
map.put(strWord,count);
}
System.out.println(map.get(strWord));
}
for(Map.Entry entry : map.entrySet())
{
System.out.println(entry);
}
}
}
Set
和LIst類似,主要區(qū)別是不能保存重復元素
生成100000個UUID,判斷是否有重復的?
Set<String> stringSetUUID = new HashSet<>();
for(int i = 0; i < 10000000; i++)
{
UUID uuid = UUID.randomUUID();
stringSetUUID.add(uuid.toString());
}
System.out.println(stringSetUUID.size());
撲克模擬問題續(xù)
隨機發(fā)出5張牌,判斷牌型





單張撲克類
package com.PokerDemo;
/**
* Created by ttc on 2018/5/28.
*/
public class Card {
private int value;
private String color;
public Card(String color,int value)
{
this.value = value;
this.color = color;
}
@Override
public String toString() {
String strValue = "";
if(value == 11)
{
strValue = "J";
}
else if(value == 12)
{
strValue = "Q";
}
else if(value == 13)
{
strValue = "K";
}
else if(value == 1)
{
strValue = "A";
}
else
{
strValue = String.valueOf(value);
}
return color + strValue;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
撲克類
package com.PokerDemo;
import java.util.*;
/**
* Created by ttc on 2018/5/28.
*/
public class Poke {
private Card[] cards = new Card[52];
private String[] colors = {"紅桃","黑桃","方片","草花"};
private int[] values = {1,2,3,4,5,6,7,8,9,10,11,12,13};
//初始化52個撲克對象
public Poke()
{
///紅桃---下標從0到12,值是從1到13
///黑桃---下標從13到25,值是從1到13
int index = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
cards[index++] = new Card(colors[i],values[j]);
}
}
// System.out.println(Arrays.toString(cards));
// cards[0] = new Card(colors[0],values[0]);
// cards[1] = new Card(colors[0],values[1]);
// //...
// cards[13] = new Card(colors[1],values[0]);
// cards[14] = new Card(colors[1],values[1]);
// //...
// cards[26] = new Card("方片",1);
}
public void output()
{
int index = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
System.out.print(cards[index++]+" ");
}
System.out.println();
}
}
public void shuffle()
{
int index = 0;
Random random = new Random();
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
//生成一個隨機下標,將隨機下標帶入到cards撲克數(shù)組中,得到一張隨機的牌
//將當前的牌和隨機出來的牌交換
int randomIndex = random.nextInt(52);
Card cardTemp = cards[index];
cards[index] = cards[randomIndex];
cards[randomIndex] = cardTemp;
}
}
}
public void judgeType(Card[] cards) {
Set<String> stringSet = new HashSet<>();
List<Integer> integerList = new ArrayList<>();
Set<Integer> integerSet = new HashSet<>();
while (true) {
for (Card card : cards) {
stringSet.add(card.getColor());
integerList.add(card.getValue());
integerSet.add(card.getValue());
}
Collections.sort(integerList);
if (stringSet.size() == 1 && (integerList.get(4) - integerList.get(0) == 4 && integerSet.size() == 5)) {
System.out.println("同花順");
return;
} else if (stringSet.size() == 1) {
System.out.println("同花");
return;
} else if ((integerList.get(4) - integerList.get(0) == 4 && integerSet.size() == 5)) {
System.out.println("順子");
return;
}
if (integerSet.size() == 5) {
System.out.println("雜牌");
return;
}
if (integerSet.size() == 4) {
System.out.println("一對");
return;
}
if (integerSet.size() == 2) {
// System.out.println("四帶一或三帶二");
// 66669 [6:4,9:1]
// 55588 [5:3,8:2]
//key是牌值,value是該牌值出現(xiàn)的次數(shù)
Map<Integer, Integer> map = new HashMap<>();
for (Card card : cards) {
if (map.containsKey(card.getValue())) {
int count = map.get(card.getValue());
count++;
map.put(card.getValue(), count);
} else {
map.put(card.getValue(), 1);
}
}
if (map.containsValue(4)) {
System.out.println("4帶1");
return;
} else {
System.out.println("3帶2");
return;
}
// map.containsValue(3)
}
if (integerSet.size() == 3) {
// System.out.println("311或221");
// 77765 [7:3,6:1,5:1]
// 88449 [8:2,4:2,9:1]
Map<Integer, Integer> map = new HashMap<>();
for (Card card : cards) {
if (map.containsKey(card.getValue())) {
int count = map.get(card.getValue());
count++;
map.put(card.getValue(), count);
} else {
map.put(card.getValue(), 1);
}
}
if (map.containsValue(3)) {
System.out.println("311");
return;
} else {
System.out.println("221");
return;
}
}
}
}
public Card[] takeOneHand()
{
Card[] cardsHand = new Card[5];
for(int i = 0; i < 5; i++)
{
cardsHand[i] = cards[i];
}
return cardsHand;
}
}
主類
package com.PokerDemo;
public class Main {
public static void main(String[] args) {
// write your code here
// Card card = new Card("黑桃",1);
// System.out.println(card);
Poke poke = new Poke();
poke.output();
poke.shuffle();
System.out.println();
poke.output();
Card[] cards = poke.takeOneHand();
poke.judgeType(cards);
}
}