Java基础学习第十三天——StringBuffer类与基本类型包装类
来源:互联网 发布:粒子群优化算法 java 编辑:程序博客网 时间:2024/05/16 09:04
StringBuffer类
StringBuffer类概述及其构造方法
StringBuffer类概述
- 线程安全的可变字符序列。
- 用字符串做拼接,比较耗时并且也耗内存,而这种拼接操作又是比较常见的,为了解决这个问题,Java就提供了一个字符串缓冲区类
StringBuffer
供我们使用。
StringBuffer和String的区别?
- 前者长度和内容可变,后者不可变。
- 如果使用前者做字符串的拼接,不会浪费太多的资源。
构造方法
- public
StringBuffer()
:无参构造方法。 - public
StringBuffer(int capacity)
:指定容量的字符串缓冲器对象。 - public
StringBuffer(String str)
:指定字符串内容的字符串缓冲器对象。
- public
StringBuffer的方法:
- public int capacity():返回当前容量。(初始值16个字符) 理论值
- public int length():返回长度(字符数)。 实际值
public class StringBufferDemo { public static void main(String[] args) { // public StringBuffer():无参构造方法 StringBuffer sb = new StringBuffer(); System.out.println("sb:" + sb); System.out.println("sb.capacity():" + sb.capacity()); System.out.println("sb.length():" + sb.length()); System.out.println("--------------------------"); // public StringBuffer(int capacity):指定容量的字符串缓冲区对象 StringBuffer sb2 = new StringBuffer(50); System.out.println("sb2:" + sb2); System.out.println("sb2.capacity():" + sb2.capacity()); System.out.println("sb2.length():" + sb2.length()); System.out.println("--------------------------"); // public StringBuffer(String str):指定字符串内容的字符串缓冲区对象 StringBuffer sb3 = new StringBuffer("hello"); System.out.println("sb3:" + sb3); System.out.println("sb3.capacity():" + sb3.capacity()); System.out.println("sb3.length():" + sb3.length()); }}/*运行结果:sb:sb.capacity():16sb.length():0--------------------------sb2:sb2.capacity():50sb2.length():0--------------------------sb3:hellosb3.capacity():21 // 16+5sb3.length():5*/
StringBuffer类的成员方法
- * 添加*功能
- public StringBuffer**
append
**(String str)- 可以把任意类型数据添加到字符串缓冲区里面,并返回
字符串缓冲区
本身
- 可以把任意类型数据添加到字符串缓冲区里面,并返回
- public StringBuffer
insert
(int offset,String str)- 在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
- public StringBuffer**
// 创建字符串缓冲区对象StringBuffer sb = new StringBuffer();//public StringBuffer append(String str)StringBuffer sb2 = sb.append("hello");//将hello添加到StringBuffer缓冲器System.out.println("sb:" + sb);System.out.println("sb2:" + sb2);System.out.println(sb == sb2); // true
StringBuffer sb = new StringBuffer();// 链式编程sb.append("hello").append(true).append(12).append(34.56);System.out.println("sb:" + sb);sb.insert(5, "world");System.out.println("sb:" + sb);
- 删除功能
- public StringBuffer
deleteCharAt
(int index)- 删除指定位置的字符,并返回本身
- public StringBuffer
delete
(int start,int end)- 删除从指定位置开始指定位置结束的内容,并返回本身(包左不包右)
- public StringBuffer
// 需求:我要删除所有的数据sb.delete(0, sb.length());System.out.println("sb:" + sb);
- 替换功能
- public StringBuffer
replace
(int start,int end,String str)- 从start开始到end用str替换
- public StringBuffer
// 需求:我要把world这个数据替换为"节日快乐"sb.replace(5, 10, "节日快乐");System.out.println("sb:" + sb);
反转功能
public StringBuffer
reverse
()
“`java
// 添加数据
sb.append(“霞青林爱我”);
System.out.println(“sb:” + sb);// public StringBuffer reverse()
sb.reverse();
System.out.println(“sb:” + sb);
/*
result:
sb:霞青林爱我
sb:我爱林青霞
*/
<br>* **截取功能** : 注意返回值类型不再是`StringBuffer`**本身**,而是<font color = red>**`String类型`**</font> * public String `substring`(int start) * public String `substring`(int start,int end) * 截取功能和前面几个功能的不同:返回值类型是`String类型`,本身**没有发生改变**```java public class StringBufferDemo { public static void main(String[] args) { // 创建字符串缓冲区对象 StringBuffer sb = new StringBuffer(); // 添加元素 sb.append("hello").append("world").append("java"); System.out.println("sb:" + sb); // 截取功能 // public String substring(int start) String s = sb.substring(5); System.out.println("s:" + s); System.out.println("sb:" + sb); // public String substring(int start,int end) String ss = sb.substring(5, 10); System.out.println("ss:" + ss); System.out.println("sb:" + sb); }}<div class="se-preview-section-delimiter"></div>
StringBuffer类练习
String和StringBuffer的相互转换
- 注意:不能把字符串的值直接赋值给StringBuffer,可通过以下两种方式进行赋值:
String
转StringBuffer
方法:- 方式1:通过
构造方法
- StringBuffer sb = new StringBuffer(s);
- 方式2:通过
append()
方法- StringBuffer sb2 = new StringBuffer();
- sb2.append(s);
- 方式1:通过
StringBuffer
转String
方法:- 注:任何引用类型调用toString方法都可以转为String类型。
- 方式1:通过
构造方法
- String str = new String(buffer);
- 方式2:通过
toString()
方法- String str2 = buffer.toString();
public class StringBufferTest { public static void main(String[] args) { // String -- StringBuffer String s = "hello"; StringBuffer sb2 = new StringBuffer(); sb2.append(s); System.out.println("sb:" + sb); System.out.println("sb2:" + sb2); System.out.println("---------------"); // StringBuffer -- String StringBuffer buffer = new StringBuffer("java"); // String(StringBuffer buffer) // 方式1:通过构造方法 String str = new String(buffer); // 方式2:通过toString()方法 String str2 = buffer.toString(); System.out.println("str:" + str); System.out.println("str2:" + str2); }}<div class="se-preview-section-delimiter"></div>
- 把数组拼接成一个字符串
public class StringBufferTest2 { public static void main(String[] args) { // 定义一个数组 int[] arr = { 44, 33, 55, 11, 22 }; //用StringBuffer做拼接的方式 String s2 = arrayToString2(arr); System.out.println("s2:" + s2); } // 用StringBuffer做拼接的方式 public static String arrayToString2(int[] arr) { StringBuffer sb = new StringBuffer(); sb.append("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { sb.append(arr[x]); } else { sb.append(arr[x]).append(", "); } } sb.append("]"); return sb.toString(); }}<div class="se-preview-section-delimiter"></div>
- 把字符串反转
public class StringBufferTest3 { public static void main(String[] args) { // 键盘录入数据 Scanner sc = new Scanner(System.in); System.out.println("请输入数据:"); String s = sc.nextLine(); // 方式1:用String做拼接 String s1 = myReverse(s); System.out.println("s1:" + s1); // 方式2:用StringBuffer的reverse()功能 String s2 = myReverse2(s); System.out.println("s2:" + s2); } // 用StringBuffer的reverse()功能 public static String myReverse2(String s) { // StringBuffer sb = new StringBuffer(); // sb.append(s); // StringBuffer sb = new StringBuffer(s); // sb.reverse(); // return sb.toString(); // 简易版 return new StringBuffer(s).reverse().toString(); } // 用String做拼接 public static String myReverse(String s) { String result = ""; char[] chs = s.toCharArray(); for (int x = chs.length - 1; x >= 0; x--) { // char ch = chs[x]; // result += ch; result += chs[x]; } return result; }}<div class="se-preview-section-delimiter"></div>
- 判断一个字符串是否是对称字符串
- 例如”abc”不是对称字符串,”aba”、”abba”、”aaa”、”mnanm”是对称字符串
public class StringBufferTest4 { public static void main(String[] args) { // 创建键盘录入对象 Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串:"); String s = sc.nextLine(); // 一个一个的比较 boolean b = isSame(s); System.out.println("b:" + b); //用字符串缓冲区的反转功能 boolean b2 = isSame2(s); System.out.println("b2:"+b2); } public static boolean isSame2(String s) { return new StringBuffer(s).reverse().toString().equals(s); } public static boolean isSame(String s) { boolean flag = true; // 把字符串转成字符数组 char[] chs = s.toCharArray(); for (int start = 0, end = chs.length - 1; start <= end; start++, end--) { if (chs[start] != chs[end]) { flag = false; break; } } return flag; }}<div class="se-preview-section-delimiter"></div>
StringBuffer类面试题
通过查看API了解一下
StringBuilder类
- 此类提供一个与
StringBuffer
兼容的 API,但不保证同步。该类被设计用作StringBuffer
的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer
要快。
- 此类提供一个与
String , StringBuffer , StringBuilder的区别
- A:
String
是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。 - B:
StringBuffer
是同步的,数据安全,效率低; - C:
StringBuilder
是不同步的,数据不安全,效率高
- A:
StringBuffer
和数组
的区别?- 二者都可以看出是一个容器,装其他的数据。
- StringBuffer的数据最终是一个字符串数据。
- 数组可以放置多种数据,但必须是同一种数据类型的。
看程序写结果:
- String作为参数传递
- StringBuffer作为参数传递
- 注意:
String
作为参数传递,效果和基本类型
作为参数传递是一样的。StringBuffer
类型调用append
方法时内存值会改变
public class StringBufferDemo { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; System.out.println(s1 + "---" + s2);// hello---world change(s1, s2); System.out.println(s1 + "---" + s2);// hello---world StringBuffer sb1 = new StringBuffer("hello"); StringBuffer sb2 = new StringBuffer("world"); System.out.println(sb1 + "---" + sb2);// hello---world change(sb1, sb2); System.out.println(sb1 + "---" + sb2);// hello---worldworld } public static void change(StringBuffer sb1, StringBuffer sb2) { sb1 = sb2;//StringBuffer类型用`=`赋值的特殊点。 sb2.append(sb1); } public static void change(String s1, String s2) { s1 = s2; s2 = s1 + s2; }}<div class="se-preview-section-delimiter"></div>
数组高级之排序和查找
排序
- 冒泡排序(必须掌握)
- 相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处
- 相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处
public class ArrayDemo { public static void main(String[] args) { // 定义一个数组 int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:"); printArray(arr); //由于我可能有多个数组要排序,所以我要写成方法 bubbleSort(arr); System.out.println("排序后:"); printArray(arr); } //冒泡排序代码 public static void bubbleSort(int[] arr){ for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } } // 遍历功能 public static void printArray(int[] arr) { System.out.print("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { System.out.print(arr[x]); } else { System.out.print(arr[x] + ", "); } } System.out.println("]"); }}<div class="se-preview-section-delimiter"></div>
- 选择排序
- 从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在了最小索引处
- 从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在了最小索引处
public class ArrayDemo { public static void main(String[] args) { // 定义一个数组 int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:"); printArray(arr); //用方法改进 selectSort(arr); System.out.println("排序后:"); printArray(arr); } public static void selectSort(int[] arr){ for(int x=0; x<arr.length-1; x++){ for(int y=x+1; y<arr.length; y++){ if(arr[y] <arr[x]){ int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } } } // 遍历功能 public static void printArray(int[] arr) { System.out.print("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { System.out.print(arr[x]); } else { System.out.print(arr[x] + ", "); } } System.out.println("]"); }}<div class="se-preview-section-delimiter"></div>
练习题:字符串排序
public class ArrayTest { public static void main(String[] args) { // 定义一个字符串 String s = "dacgebf"; // 把字符串转换为字符数组 char[] chs = s.toCharArray(); // 把字符数组进行排序 bubbleSort(chs); //把排序后的字符数组转成字符串 String result = String.valueOf(chs); //输出最后的字符串 System.out.println("result:"+result); } // 冒泡排序 public static void bubbleSort(char[] chs) { for (int x = 0; x < chs.length - 1; x++) { for (int y = 0; y < chs.length - 1 - x; y++) { if (chs[y] > chs[y + 1]) { char temp = chs[y]; chs[y] = chs[y + 1]; chs[y + 1] = temp; } } } }}<div class="se-preview-section-delimiter"></div>
查找
基本查找: 数组元素无序
public static int getIndex(int[] arr,int value) { int index = -1; for(int x=0; x<arr.length; x++) { if(arr[x] == value) { index = x; break; } } return index;}<div class="se-preview-section-delimiter"></div>
二分查找(折半查找) : 数组元素有序
public class ArrayDemo { public static void main(String[] args) { //定义一个数组 int[] arr = {11,22,33,44,55,66,77}; //写功能实现 int index = getIndex(arr, 33); System.out.println("index:"+index); //假如这个元素不存在后有什么现象呢? index = getIndex(arr, 333); System.out.println("index:"+index); } /* * 两个明确: * 返回值类型:int * 参数列表:int[] arr,int value */ public static int getIndex(int[] arr,int value){ //定义最大索引,最小索引 int max = arr.length -1; int min = 0; //计算出中间索引 int mid = (max +min)/2; //拿中间索引的值和要查找的值进行比较 while(arr[mid] != value){ if(arr[mid]>value){ max = mid - 1; }else if(arr[mid]<value){ min = mid + 1; } //加入判断 if(min > max){ return -1; } mid = (max +min)/2; } return mid; }}<div class="se-preview-section-delimiter"></div>
Arrays类
Arrays类概述
- 针对数组进行操作的工具类。提供了
排序
,查找
等功能。
Arrays类常用方法
- public static String
toString
(int[] a):把数组转为字符串 - public static void
sort
(int[] a):对数组进行排序 - public static int
binarySearch
(int[] a,int key):二分查找
常用方法源码详细解释
- public static String toString(int[] a)
- public static int binarySearch(int[] a,int key)
基本类型包装类
基本类型包装类概述
- 将基本数据类型封装成对象的好处:可以在对象中定义更多的功能方法操作该数据。
- 常用的操作之一:用于基本数据类型与字符串之间的转换。
基本类型
和包装类
的对应- byte <—> Byte
- short <—> Short
- int <—> Integer
- long <—> Long
- float <—> Float
- double <—> Double
- char <—> Character
- boolean <—> Boolean
Integer类
Integer类概述
- Integer类概述
- Integer 类在对象中包装了一个基本类型
int
的值 - 该类提供了多个方法,能在
int
类型和String
类型之间互相转换,还提供了处理int
类型时非常有用的其他一些常量和方法。
- Integer 类在对象中包装了一个基本类型
Integer类构造方法
- public Integer(int value)
- public Integer(String s)
- 注:这个字符串必须是由数字字符串组成。
Integer类成员方法
- int 转成 String类型:
String.valueOf
int number = 100; // 方式1 String s1 = "" + number; System.out.println("s1:" + s1); // 方式2(最优) String s2 = String.valueOf(number); System.out.println("s2:" + s2); // 方式3 // int -- Integer -- String Integer i = new Integer(number); String s3 = i.toString(); System.out.println("s3:" + s3); // 方式4 // public static String toString(int i) String s4 = Integer.toString(number); System.out.println("s4:" + s4); System.out.println("-----------------");<div class="se-preview-section-delimiter"></div>
- String 转成 int类型:
Integer.parseInt
// String -- int String s = "100"; // 方式1 // String --> Integer --> int Integer ii = new Integer(s); // public int intValue() int x = ii.intValue(); System.out.println("x:" + x); //方式2(非常重要) //public static int parseInt(String s) int y = Integer.parseInt(s); System.out.println("y:"+y);<div class="se-preview-section-delimiter"></div>
int 与 String 转换的常用方法
- public int intValue()
- public static int parseInt(String s)
- public static String toString(int i)
- public static Integer valueOf(int i)
- public static Integer valueOf(String s)
常用的基本进制转换
- public static String toBinaryString(int i)
- public static String toOctalString(int i)
- public static String toHexString(int i)
十进制到其他进制
- public static String toString(int i,int radix)
- 其他进制到十进制
- public static int parseInt(String s,int radix)
JDK5的新特性
- 自动装箱:把基本类型转换为包装类类型;
自动拆箱:把包装类类型转换为基本类型
JDK1.5以后,简化了定义方式。
- Integer x = new Integer(4);可以直接写成
- Integer x = 4;//自动装箱。
- x = x + 5;//自动拆箱。通过intValue方法。
- 需要注意:
- 在使用时,Integer x = null;上面的代码就会出现NullPointerException。
public class IntegerDemo { public static void main(String[] args) { // 定义了一个int类型的包装类类型变量i // Integer i = new Integer(100); Integer ii = 100; ii += 200; System.out.println("ii:" + ii); // 通过反编译后的代码 // Integer ii = Integer.valueOf(100); //自动装箱 // ii = Integer.valueOf(ii.intValue() + 200); //自动拆箱,再自动装箱 // System.out.println((new StringBuilder("ii:")).append(ii).toString()); Integer iii = null; // NullPointerException if (iii != null) { iii += 1000; System.out.println(iii); } }}<div class="se-preview-section-delimiter"></div>
Integer的面试题
- Integer i = 1; i += 1;做了哪些事情
- 缓冲池(看程序写结果)
- 注意:Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据
public class IntegerDemo { public static void main(String[] args) { Integer i1 = new Integer(127); Integer i2 = new Integer(127); System.out.println(i1 == i2); System.out.println(i1.equals(i2)); System.out.println("-----------"); Integer i3 = new Integer(128); Integer i4 = new Integer(128); System.out.println(i3 == i4); System.out.println(i3.equals(i4)); System.out.println("-----------"); Integer i5 = 128; Integer i6 = 128; System.out.println(i5 == i6); System.out.println(i5.equals(i6)); System.out.println("-----------"); Integer i7 = 127; Integer i8 = 127; System.out.println(i7 == i8); System.out.println(i7.equals(i8)); // 通过查看源码,我们就知道了,针对-128到127之间的数据,做了一个数据缓冲池,如果数据是该范围内的,每次并不创建新的空间 // Integer ii = Integer.valueOf(127); }}/*运行结果:false<div class="se-preview-section-delimiter"></div>true-----------false<div class="se-preview-section-delimiter"></div>true-----------false<div class="se-preview-section-delimiter"></div>true-----------truetrue*/<div class="se-preview-section-delimiter"></div>
Character类
Character类概述
- Character 类在对象中包装一个基本类型 char 的值,此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然。
Character类构造方法
- 构造方法
- public Character(char value)
Character类成员方法
- public static boolean
isUpperCase(char ch)
- public static boolean
isLowerCase(char ch)
- public static boolean
isDigit(char ch)
- public static char
toUpperCase(char ch)
- public static char
toLowerCase(char ch)
练习题
- 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public static void main(String[] args) { // 定义三个统计变量。 int bigCount = 0; int smallCount = 0; int numberCount = 0; // 键盘录入一个字符串。 Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串:"); String line = sc.nextLine(); // 把字符串转换为字符数组。 char[] chs = line.toCharArray(); // 遍历字符数组获取到每一个字符 for (int x = 0; x < chs.length; x++) { char ch = chs[x]; // 判断该字符 if (Character.isUpperCase(ch)) { bigCount++; } else if (Character.isLowerCase(ch)) { smallCount++; } else if (Character.isDigit(ch)) { numberCount++; } } // 输出结果即可 System.out.println("大写字母:" + bigCount + "个"); System.out.println("小写字母:" + smallCount + "个"); System.out.println("数字字符:" + numberCount + "个"); }}
1 0
- Java基础学习第十三天——StringBuffer类与基本类型包装类
- 黑马程序员——java第十三天:String类、StringBuffer、StringBuilder、基本数据类型对象包装类、进制转换
- 黑马程序员——java基础学习--String类,StringBuffer和基本数据包装类
- JAVA基础:StringBuffer\基本数据类型与包装类
- JAVA基础学习(十三)--String、StringBuilder、StringBuffer与包装类
- 常用API——String、StringBuffer与基本类型包装类
- java基础之基本类型与包装类
- 黑马程序员——Java基础:String类、StringBuffer、基本数据类型对象包装类
- Java基础-基本类型包装类
- 常见对象StringBuffer、Arrays类和基本类型包装类+JAVA学习笔记-DAY13
- Java学习笔记5——基本类型与包装类
- day13(StringBuffer,Arrays,基本类型包装类)
- Java基础:String、StringBuffer、基本数据类型包装类
- java基础4:String与StringBuffer及基本数据类型包装类
- 黑马程序员——Java基础---StringBuffer、Arrays、包装类
- Java基本类型与包装类
- Java基本类型与包装类
- Java基本类型与包装类
- GLES3使用GPGPU记录
- Spring MVC - HTTP Status 500 - Servlet.init() for servlet loginDispacher threw exception
- Git Bash简明教程
- 线程(二)--线程控制-后台线程
- iOS 多线程 进程、线程、并发、串行、同步、异步—— iOS 编码复习(四)(多线程2)
- Java基础学习第十三天——StringBuffer类与基本类型包装类
- c++运算符重载实例
- spring服务器乱码问题
- RMReport 报表安装说明
- NSDictionary,NSArray,NSSet简介
- c++使用Lua
- word文件保存到数据库,读取
- spring定时任务
- [LeetCode]139. Word Break