Java基础10-集合
作业回顾
蜜蜂和熊的生产消费关系,熊在蜂蜜满10斤吃掉。蜜蜂一次生产一斤蜂蜜,且蜜蜂生成一斤蜂蜜花费的时间是10s。
十只蜜蜂和两只熊。蜜蜂
bag: 20
每次产1,耗时10ms
满5的时候给蜜罐添加蜜罐
max : 30熊
eat//蜜蜂线程
public class Bee extends Thread{
public static final int BAG=20;
private int currentCount = 0;
private String name;
private Pool pool; public Bee(String name,Pool pool){
this.name = name;
this.pool = pool;
}
public void run(){
while(true){
synchronized(pool){
//如果蜜罐当前量已满
if(pool.currentNo>=Pool.MAX){
//如果蜜蜂自身蜜囊已满,通知熊吃蜂蜜,并进入等待队列
if(currentCount>=Bee.BAG){
try{
pool.notifyAll();
pool.wait();
}catch(Exception e){
}
}
//如果蜜蜂自身蜜囊未满,通知熊吃蜂蜜,自身蜜囊加1
else{
pool.notifyAll();
currentCount++;
}
}
//如果蜜罐未满
else{
//蜜罐剩余的空间
int count = Pool.MAX-pool.currentNo;
//如果蜜蜂自身的量超过蜜罐剩余空间,则将蜜罐加满,自身的量相应减少
if(currentCount>=count){
pool.currentNo = Pool.MAX;
currentCount = currentCount -count;
pool.notifyAll();
}
//如果蜜罐自身的量不够蜜罐剩余空间,则全部加入到蜜罐中,自身的量清零
else{
pool.currentNo += currentCount;
currentCount = 0;
}
}
}
}
}
} //熊线程
public class Bear extends Thread{
private String name;
private Pool pool; public Bear(String name, Pool pool){
this.name = name;
this.pool = pool;
}
public void run(){
while(true){
synchronized(pool){
if(pool.currentNo==Pool.MAX){
System.out.println(name+"吃了蜂蜜:"+ pool.currentNo);
pool.currentNo = 0;
pool.notifyAll();
}
else{
try{
pool.wait();
}
catch(Exception e){
}
}
}
}
}
} //蜜罐类
public class Pool{
public static final int MAX=30;
public int currentNo = 0;
} //测试类
public class App{
public static void main(String[] args){
Pool pool = new pool();
Bee bee1 = new Bee("bee-1",pool);
Bee bee2 = new Bee("bee-2",pool);
Bee bee3 = new Bee("bee-3",pool);
Bee bee4 = new Bee("bee-4",pool);
Bee bee5 = new Bee("bee-5",pool);
Bee bee6 = new Bee("bee-6",pool);
Bee bee7 = new Bee("bee-7",pool);
Bee bee8 = new Bee("bee-8",pool); Bear bear1 = new Bear("bear-1",pool); bee1.start();
bee2.start();
bee3.start();
bee4.start();
bee5.start();
bee6.start();
bee7.start();
bee8.start(); bear1.start();
}
}
取出两个字符串中最大的公共子串。
public class subStringDemo {
public static void main(String[] args) { String str1 = "how中are国you123";
String str2 = "your国are国howu123"; //System.out.println(str1.compareTo(str2));
//String str3 = str1-str2; char c='a'; //System.out.println(str1.lastIndexOf(c));
//System.out.println(str1.substring(0,str1.length())); System.out.println(str1.charAt(0));
System.out.println(getMaxSameStr(str1,str2));//are国
} /**
* Find the max same subString of two strings
* */
public static String getMaxSameStr(String str1,String str2) {
String maxSameStr="";
String temp="";
int len = str1.length();
//从大到小在str1中取子串,和str2匹配
// 缺陷,当有两个同样长度的公共子串时,只能找到前面一个
for(int i=0;i<len;i++) {
for (int j=0;j<=i;j++) {
temp = str1.substring(j,j+len-i);
if(str2.indexOf(temp)!=-1) {
maxSameStr=temp;
return maxSameStr;
}
}
}
return maxSameStr;
}
}
StringBuffer是线程安全的,StringBuilder不是线程安全。单线程访问情况下,性能是否一致?
public class StringBuilderBuffer {
public static void main(String[] args) {
//测试单线程访问情况下,StringBuilder与 StringBuffer的性能
StringBuilder str1 = new StringBuilder();
StringBuffer str2 = new StringBuffer(); long l1 = System.currentTimeMillis();
for(int i=0;i<1000000;i++) {
str1.append(i);
}
System.out.println(System.currentTimeMillis()-l1);//272 long l2 = System.currentTimeMillis();
for(int j=0;j<1000000;j++) {
str2.append(j);
}
System.out.println(System.currentTimeMillis()-l2);//434, StringBuffer是线程安全的,其方法中有同步这一步骤,因此访问较慢
}
}
完成8种基本数据类包装类的练习,完成自动拆装箱操作。
import java.io.UnsupportedEncodingException; public class StringDemo {
public static void main(String[] args) throws Exception {
String str = "한국어";
byte[] b = str.getBytes("euc_kr");
/*
int count = 0;
for(int i=0;i<=0xffff;i++) {
count++;
System.out.print((char)i);
if(count>=20) {
count = 0;
System.out.println();
}
}
*/
System.out.println(new String(b,"euc_kr"));//한국어 //字符串倒序输出,不支持中文
String str2 = "abcde123";
byte[] b2 = str2.getBytes("utf-8");
byte[] b3 = new byte[b2.length];
for(int i = 0;i<b2.length;i++) {
b3[i] = b2[b2.length-i-1];
}
System.out.println(new String(b3,"utf-8"));//321edcba
//自动装箱
Integer a = 12;
System.out.println(a);//12
//自动拆箱
int i = a;
System.out.println(i);//12
}
}
substring(String str, int beginIndex, int length);
返回一定长度的子串/**
* return subString of String based on the given beginIndex and length
* */
public static String subString(String str, int beginIndex, int length){
String subStr = null;
if(str==null || str.length()==0) {
System.out.println("字符串非法");
return null;
}
if(beginIndex<0 || beginIndex>=str.length()) {
System.out.println("开始索引非法");
return null;
} if(length<=0 || beginIndex+length>str.length()) {
System.out.println("长度非法");
return null;
}
return str.substring(beginIndex,beginIndex+length);
}
找到自己名字对应的Unicode码
for(int i=0;i<=0xffff;i++) {
if((char)i=='翟') {
System.out.println(i);
int2hex(i);
System.out.println((char)i);
}
if((char)i=='大') {
System.out.println(i);
int2hex(i);
System.out.println((char)i);
}
if((char)i=='壮') {
System.out.println(i);
int2hex(i);
System.out.println((char)i);
}
} public static void int2hex(int l) {
char hex[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
System.out.print("0x");
for(int i=28;i>=0;i=i-4) {
System.out.print(hex[(l>>i)&0x0f]);
}
System.out.println();
}
StringBuffer
字符串缓冲区
mutable, 可变的
java.lang.AbstractStringBuilder
|--------java.lang.StringBuffer
线程安全的
StringBuilder
字符串构建器
mutable, 可变的
java.lang.AbstractStringBuilder
|--------java.lang.StringBuilder
线程不安全
集合类
List : 列表,接口 ArrayList()
interface java.lang.Iterable
/|\
|------interface java.util.Collection
/|\
|-----interface java.util.List
|---------------class java.util.ArrayList
ArrayList读取快,写入慢
list.add(...);
list.get(int index);
list.remove(int index);
list.clear();
LinkedList
存储速度快,查询速度慢
链表,手拉手实现的对象引用
[]数组
length //长度属性
String
length() //方法.
- ==判断的是对象的内存地址,不是对象的内容
- equals方法判断是对象的内容是否相同
interface Collection
size() //方法
isEmpty() // ==null ?
判断集合有效性
col != null && col.isEmpty()contains(Object obj) //判断是否包含指定的对象
List //有序,可重复
Set //无序,不重复
Map //key-value
instanceof(非精准判断)
运算符,判断变量是否是指定类型的对象。
boolean b = obj instanceof String ;
String 是final类,不可以被继承精准判断须用:
this.getClass()==obj.getClass();
练习
创建集合
存放String[tom,tomas,tomsLee]
存放Integer[100,200,300]
存放Student{name,sex,age,标准javabean}[tom,tomas,tomsLee]
List list = new ArrayList();
//存放String
list.add("tom");
list.add("tomas");
list.add("tomslee"); //存放Integer
list.add(100);
list.add(new Integer(200));
list.add(300); //存放Student
list.add(new Student("s-1",10,'f'));
Student s = new Student("s-2",11,'m');
list.add(s);
list.add(new Student("s-3",12,'m')); Object obj = null;
//利用索引遍历列表
for(int i=0;i<list.size();i++) {
obj = list.get(i);
if(obj instanceof String) {
System.out.println((String)obj);
}
else if(obj instanceof Integer) {
System.out.println(100+(Integer)obj);
}
else {
Student s2 = (Student)obj;
System.out.println("name:"+s2.getName()+" age:"+s2.getAge()+" sex:"+s2.getSex());
}
}
System.out.println("------------------");
//利用迭代器遍历列表
Iterator it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
Student :
判断学生类对象内容是否相同,重写equals方法。需要三个条件同时满足name + age + sex都相同才相同。public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(obj==this) {
return true;
} if(obj.getClass() == Student.class ) {
Student s = (Student)obj;
boolean nameEqu = false;
boolean ageEqu = false;
boolean sexEqu = false; if(s.getName()==null) {
if(this.getName()==null) {
nameEqu = true;
}
else {
nameEqu = false;
}
}
else {
nameEqu = s.getName().equals(this.name);
}
/*if(this.age==s.getAge()) {
ageEqu = true;
}*/
ageEqu = (this.age==s.getAge());
/*if(this.sex == s.getSex()) {
sexEqu = true;
}*/
sexEqu = (this.sex == s.getSex());
return nameEqu && ageEqu && sexEqu;
}
return false;
}
练习Vector向量类。
//与AarryList的不同点在于,Vector是线程安全的
Vector vector = new Vector();
Student s1 = new Student("s1",10);
//向集合中添加元素
vector.add(s1);
vector.add(new Student("s2",20)); //重复添加元素
//添加的是重复的地址,匿名对象添加的是新地址(就算重写了equals方法,也是新地址)
vector.add(s1);
vector.add(new Student("s1",10));
vector.add(new Student("s2",20)); System.out.println("重复添加元素,重写equals方法");
Iterator it = vector.iterator();
while(it.hasNext()) {
System.out.println(it.next());
} Student2 s2 = new Student2("s3",10);
vector.add(s2);
vector.add(s2);
vector.add(new Student2("s3",10)); System.out.println("重复添加元素,没有重写equals方法");
it = vector.iterator();
while(it.hasNext()) {
System.out.println(it.next());
} //在指定位置插入元素,后续元素往后串
vector.add(0, new Student("s3",30));
//索引越界异常
//vector.add(10,new Student("s4",30));
System.out.println("在指定位置插入元素");
it = vector.iterator();
while(it.hasNext()) {
System.out.println(it.next());
} //删除元素,后续元素往前串
System.out.println("按索引删除元素");
vector.remove(0);
it = vector.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
作业:
remove(int index); //删除指定位置的元素
remove(Object o); //删除指定对象,考虑删除对象的规则是什么?
removeAll(Collection col);//删除指定集合中的所有元素。
contains(Object o); //是否包含
contains(Collection col); //是否包含集合。
Java基础10-集合的更多相关文章
- java基础-Map集合
java基础-Map集合 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Map集合概述 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它 ...
- 第6节:Java基础 - 三大集合(上)
第6节:Java基础 - 三大集合(上) 本小节是Java基础篇章的第四小节,主要介绍Java中的常用集合知识点,涉及到的内容包括Java中的三大集合的引出,以及HashMap,Hashtable和C ...
- Java基础之 集合体系结构(Collection、List、ArrayList、LinkedList、Vector)
Java基础之 集合体系结构详细笔记(Collection.List.ArrayList.LinkedList.Vector) 集合是JavaSE的重要组成部分,其与数据结构的知识密切相联,集合体系就 ...
- 备战金三银四!一线互联网公司java岗面试题整理:Java基础+多线程+集合+JVM合集!
前言 回首来看2020年,真的是印象中过的最快的一年了,真的是时间过的飞快,还没反应过来年就夸完了,相信大家也已经开始上班了!俗话说新年新气象,马上就要到了一年之中最重要的金三银四,之前一直有粉丝要求 ...
- java基础技术集合面试【笔记】
java基础技术集合面试[笔记] Hashmap: 基于哈希表的 Map 接口的实现,此实现提供所有可选的映射操作,并允许使用 null 值和 null 键(除了不同步和允许使用 null 之外,Ha ...
- Java基础--说集合框架
版权所有,转载注明出处. 1,Java中,集合是什么?为什么会出现? 根据数学的定义,集合是一个元素或多个元素的构成,即集合一个装有元素的容器. Java中已经有数组这一装有元素的容器,为什么还要新建 ...
- JAVA基础学习-集合三-Map、HashMap,TreeMap与常用API
森林森 一份耕耘,一份收获 博客园 首页 新随笔 联系 管理 订阅 随笔- 397 文章- 0 评论- 78 JAVA基础学习day16--集合三-Map.HashMap,TreeMap与常用A ...
- 《回炉重造 Java 基础》——集合(容器)
整体框架 绿色代表接口/抽象类:蓝色代表类. 主要由两大接口组成,一个是「Collection」接口,另一个是「Map」接口. 前言 以前刚开始学习「集合」的时候,由于没有好好预习,也没有学好基础知识 ...
- java基础之集合长度可变的实现原理
首先我们要明白java中的集合Collection,List,ArrayList之间的关系: ArrayList是具体的实现类,实现了List接口 List是接口,继承了Collection接口 Li ...
- java基础(10)---leetcode的String、数组以及集合的一些使用
整数 一.整数反转_7 /* 12345 变成 54321 */ public class 整数反转_7 { public static void main(String[] args){ int x ...
随机推荐
- RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your c
Error Msg: Traceback (most recent call last): File "<string>", line 1, in <module ...
- redis简介与持久化
一 . redis简介 redis属于NoSQL学名(not only sql) 特点: 存储结构与mysql这一种关系型数据库完全不同,nosql存储的是key value形式 nosql有很多产品 ...
- MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码';
- Python——爬虫——数据提取
一.XML数据提取 (1)定义:XML指可扩展标记语言.标记语言,标签需要我们自行定义 (2)设计宗旨:是传输数据,而非显示数据,具有自我描述性 (3)节点关系: 父:每个元素及属性都有一个父. ...
- CentOS修改SSH端口号和禁止root用户直接登录
linux安装ssh远程登录后,为了安全起见,修改默认的22端口号并禁止root用户直接通过ssh登录. 配置方法如下: 1.使用vi编辑器打开ssh配置文件 /etc/ssh/sshd_config ...
- iOS Button添加阴影 和 圆角
用iamgeview 加手势代替 self.headimageview = [[UIImageView alloc] initWithFrame:CGRectMake(IPHONEWIDTH(13), ...
- ListView与RecyclerView对比浅析——缓存机制
https://www.jianshu.com/p/193fb966e954 一,背景 RecyclerView是谷歌官方出的一个用于大量数据展示的新控件,可以用来代替传统的ListView,更加强大 ...
- JS判断浏览器是否支持触屏事件
var hasTouch=function(){ var touchObj={}; touchObj.isSupportTouch = "ontouchend" in docume ...
- 【LR9】【LOJ561】CommonAnts 的调和数 数论 筛法
题目大意 有一个长度为 \(n\) 的序列. 有 \(m\) 次修改,每次给你 \(x,y\),令 \(\forall 1\leq i\leq \lfloor\frac{n}{x}\rfloor,a_ ...
- Java多线程编程-线程之间的通信
转载自:这里 学习了基础的线程知识 看到了 线程之间的通信 线程之间有哪些通信方式呢? 1.同步 这里讲的同步是指多个线程通过synchronized关键字这种方式来实现线程间的通信. public ...