文章目录
引用类型数组
// list中只能装引用数据类型,不能装基本数据类型
//Number类
/*基本数据类型 包装类
* byte Byte
* short Short
* int Integer(特殊)
* long Long
* float Float
* double Double
* char Character(特殊)
* boolean Boolean
*/
- 先创建一个标准类Person:
package com.zcl.classcode.D07;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
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 "Person [name=" + name + ", age=" + age + "]";
}
}
- 引用类型数组使用方法:
package com.zcl.classcode.D07;
public class DemoArray {
public static void main(String[] args) {
//首先创建一个长度为3的数组,里面用来存放Person类型的对象
Person[] array = new Person[3];
Person one = new Person("许嵩",28);
Person two = new Person("周杰伦",34);
Person three = new Person("林俊杰",38);
array[0] = one;
array[1] = two;
array[2] = three;
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
}
}
ArrayList集合:
package com.zcl.classcode.D07;
import java.util.ArrayList;
public class DemoArrayList {
public static void main(String[] args) {
//<E>:泛型
ArrayList list = new ArrayList();
System.out.println(list);
list.add(new Person("王力宏",30));
list.add("你很帅哦!");
list.add(1000);
System.out.println(list);
System.out.println("=============");
System.out.println(list.get(0));
Person p = (Person)list.get(0);
String s = (String) list.get(1);
int i = (int) list.get(2);
System.out.println(p);
System.out.println(s);
System.out.println(i);
ArrayList<String> list = new ArrayList<>();
System.out.println(list);//[]
list.add("123");
System.out.println(list);
String s = list.get(0);
// String s = (String)list.get(2);
}
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
System.out.println(list);
list.add(new Person("迪丽热巴", 18));
System.out.println(list);
list.add("古力娜扎");
list.add("玛尔扎哈");
System.out.println(list); //
Person p = (Person) list.get(0);
Person s = (Person) list.get(1);
System.out.println(p);
System.out.println(s);
}
/*
题目:
定义一个数组,用来存储3个Person对象。
数组有一个缺点:一旦创建,程序运行期间长度不可以发生改变。
*/
public class Demo01Array {
public static void main(String[] args) {
// 首先创建一个长度为3的数组,里面用来存放Person类型的对象
Person[] array = new Person[3];
Person one = new Person("迪丽热巴", 18);
Person two = new Person("古力娜扎", 28);
Person three = new Person("玛尔扎哈", 38);
// 将one当中的地址值赋值到数组的0号元素位置
array[0] = one;
array[1] = two;
array[2] = three;
System.out.println(array[0]); // 地址值
System.out.println(array[1]); // 地址值
System.out.println(array[2]); // 地址值
System.out.println(array[1].getName()); // 古力娜扎
}
}
数组的长度不可以发生改变。
但是ArrayList集合的长度是可以随意变化的。
对于ArrayList来说,有一个尖括号代表泛型。
泛型:也就是装在集合当中的所有元素,全都是统一的什么类型。
注意:泛型只能是引用类型,不能是基本类型。
注意事项:
对于ArrayList集合来说,直接打印得到的不是地址值,而是内容。
如果内容是空,得到的是空的中括号:[]
public class Demo02ArrayList {
public static void main(String[] args) {
// 创建了一个ArrayList集合,集合的名称是list,里面装的全都是String字符串类型的数据
// 备注:从JDK 1.7+开始,右侧的尖括号内部可以不写内容,但是<>本身还是要写的。
ArrayList<String> list = new ArrayList<>();
System.out.println(list); //
// 向集合当中添加一些数据,需要用到add方法。
list.add("赵丽颖");
System.out.println(list); // [
list.add("迪丽热巴");
list.add("古力娜扎");
list.add("玛尔扎哈");
System.out.println(list); //
for(int i = 0 ; i <list.size();i++) {
System.out.println(list.get(i));
}
System.out.println("========================");
for (String s : list) {
System.out.println(s);
}
// list.add(new Person("迪丽热巴", 18));
// list.add(100); //
}
}
ArrayList当中的常用方法:
public boolean add(E e):向集合当中添加元素,参数的类型和泛型一致。返回值代表添加是否成功。
备注:对于ArrayList集合来说,add添加动作一定是成功的,所以返回值可用可不用。
但是对于其他集合(今后学习)来说,add添加动作不一定成功。
public E get(int index):从集合当中获取元素,参数是索引编号,返回值就是对应位置的元素。
public E remove(int index):从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素。
public int size():获取集合的尺寸长度,返回值是集合中包含的元素个数。
public class Demo03ArrayListMethod {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
System.out.println(list); // []
// 向集合中添加元素:add
boolean success = list.add("柳岩");
System.out.println(list); //
System.out.println("添加的动作是否成功:" + success); //
list.add("高圆圆");
list.add("赵又廷");
list.add("李小璐");
list.add("贾乃亮");
System.out.println(list); //
// 从集合中获取元素:get()。索引值从0开始
String name = list.get(2);
System.out.println("第2号索引位置:" + name); //
// 从集合中删除元素:remove()。索引值从0开始。
String whoRemoved = list.remove(3);
System.out.println("被删除的人是:" + whoRemoved); //
System.out.println(list); //
// 获取集合的长度尺寸,也就是其中元素的个数
int size = list.size();
System.out.println("集合的长度是:" + size);
}
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("迪丽热巴");
list.add("古力娜扎");
list.add("玛尔扎哈");
// 遍历集合
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。
基本类型 包装类(引用类型,包装类都位于java.lang包下)
byte Byte
short Short
int Integer 【特殊】
long Long
float Float
double Double
char Character 【特殊】
boolean Boolean
从JDK 1.5+开始,支持自动装箱、自动拆箱。
自动装箱:基本类型 --> 包装类型
自动拆箱:包装类型 --> 基本类型
public class Demo05ArrayListBasic {
public static void main(String[] args) {
ArrayList<String> listA = new ArrayList<>();
// ArrayList<int> listB = new ArrayList<>();
ArrayList<Integer> listC = new ArrayList<>();
Integer i = new Integer(10);
listC.add(i);
listC.add(100);//自动装箱 int -》 Integer
listC.add(200);
System.out.println(listC); // [10, 100, 200]
int num = listC.get(1);//自动拆箱 Integer -》 int
System.out.println("第1号元素是:" + num);
}
}
ArrayList小练习
1.题目:
生成6个1~33之间的随机整数,添加到集合,并遍历集合。
思路:
1.for循环
2.Random nextInt(33)+1
3.ArrayList<Integer>
4.foreach
*/
public class Demo01ArrayListRandom {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Random r = new Random();
for (int i = 0; i < 6; i++) {
int a = r.nextInt(33)+1;
list.add(a);
}
for (Integer i : list) {
System.out.println(i);
}
}
}
2.题目:
自定义4个学生对象,添加到集合,并遍历。
思路:
1. 自定义Student学生类,四个部分。
2. 创建一个集合,用来存储学生对象。泛型:<Student>
3. 根据类,创建4个学生对象。
4. 将4个学生对象添加到集合中:add
5. 遍历集合:for、size、get
*/
public class Demo02ArrayListStudent {
public static void main(String[] args) {
Student one = new Student("洪七公", 20);
Student two = new Student("欧阳锋", 21);
Student three = new Student("黄药师", 22);
Student four = new Student("段智兴", 23);
ArrayList<Student> list = new ArrayList<Student>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
for (Student student : list) {
System.out.println(student);
}
}
}
3.题目:
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用{}扩起集合,使用@分隔每个元素。
格式参照 {元素@元素@元素}。
System.out.println(list); [10, 20, 30]
printArrayList(list); {10@20@30}
思路:
定义一个ArrayList<Integer>
遍历集合
*/
public class Demo03ArrayListPrint {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
printArrayList(list);
}
/*
* 返回值: void
* 参数: ArrayList<Integer>
*/
public static void printArrayList(ArrayList<Integer> l) {
System.out.print("{");
for (int i = 0; i < l.size(); i++) {
if (i == l.size()-1) {
System.out.print(l.get(i) + "}");
}else {
System.out.print(l.get(i) + "@");
}
}
}
}
4.题目:
用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中。
要求使用自定义的方法来实现筛选。
分析:
1.for Random
2.ArrayList<Integer> listBig
3.调用方法,传参listBig
4.创建一个ArrayList<Integer> listSmall
5.遍历listBig,判断偶数
6.如果是偶数,就存入listSmall
*/
public class Demo04ArrayListReturn {
public static void main(String[] args) {
ArrayList<Integer> listBig = new ArrayList<Integer>();
Random r = new Random();
for (int i = 0; i < 20; i++) {
int a = r.nextInt(101);
listBig.add(a);
}
System.out.println(listBig);
ArrayList<Integer> listSmall = getSmallArray(listBig);
System.out.println(listSmall);
}
public static ArrayList<Integer> getSmallArray(ArrayList<Integer> listB) {
ArrayList<Integer> listSmall = new ArrayList<Integer>();
for (int i = 0; i < listB.size(); i++) {
if (listB.get(i) %2 == 0 ) {
listSmall.add(listB.get(i));
}
}
return listSmall;
}
}
String类
String类基本使用方法:
java.lang.String类代表字符串。
API当中说:Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
也就是说:java中每一个""双引号引起来的字符串都是一个对象
字符串的特点:
- 字符串的内容永不可变。【重点】
- 字符串效果上相当于是char[]字符数组,但是底层原理是byte[]字节数组。
创建字符串的常见3+1种方式。
三种构造方法:
public String():创建一个空白字符串,不含有任何内容。
public String(char[] array):根据字符数组的内容,来创建对应的字符串。
public String(byte[] array):根据字节数组的内容,来创建对应的字符串。
一种直接创建:
String str = “Hello”; // 右边直接用双引号
注意:直接写上双引号,就是字符串对象。
public class Demo01String {
public static void main(String[] args) {
// 使用空参构造
String str1 = new String(); // 小括号留空,说明字符串什么内容都没有。
System.out.println("第1个字符串:" + str1);
String s1 = "abc";
s1 = "abd";
System.out.println(s1);
// 根据字符数组创建字符串
char[] charArray = { 'A', 'B', 'C' };
String str2 = new String(charArray);
System.out.println("第2个字符串:" + str2);
// 根据字节数组创建字符串
byte[] byteArray = { 97, 98, 99 };
String str3 = new String(byteArray);
System.out.println("第3个字符串:" + str3);
// 直接创建
String str4 = "Hello";
System.out.println("第4个字符串:" + str4);
}
}
/*
* String类的变量定义方式:3+1种
* 1种:String s = "abc";
* 3种: (1) new String(String s)
* (2)new String (char[] c)
* (3)new String(byte[] b)
*/
public class Test {
public static void main(String[] args) {
// String s = "abc";
String s = "ABC";
// new String(String s)
String s2 = new String("abc");
System.out.println(s2);
// new String (char[] c)
char[] cArr = { 'a', 'b', 'd' };
String s3 = new String(cArr);
System.out.println(s3);
// new String(byte[] b)
byte[] bArr = { 65, 66, 97 };
String s4 = new String(bArr);
System.out.println(s4);
}
}
String类常用方法:
equals()方法
对于引用数据类型:==是进行对象的地址值比较,如果确实需要字符串的内容比较,可以使用两个方法:
public boolean equals(Object obj):参数可以是任何对象,只有参数的内容相同的才会给true;否则返回false。
注意事项:
- 参数为Object,表示可以传任意类型的对象。
- equals方法具有对称性,也就是a.equals(b)和b.equals(a)效果一样。
- 如果比较双方一个常量一个变量,推荐把常量字符串写在前面。
推荐:“abc”.equals(str) 不推荐:str.equals(“abc”)
public boolean equalsIgnoreCase(String str):忽略大小写,进行内容比较。
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(charArray);
System.out.println(str1.equals(str2)); // true
System.out.println(str2.equals(str3)); // true
System.out.println(str3.equals("Hello")); // true
System.out.println("Hello".equals(str1)); // true
Student student = new Student();
System.out.println("比较"+str2.equals(student)); // false
String str4 = "hello";//严格区分大小写
System.out.println(str1.equals(str4)); // false
System.out.println("=================");
String str5 = null;
System.out.println("abc".equals(str5)); // false
System.out.println(str5.equals("abc")); //
System.out.println("=================");
String strA = "Java";
String strB = "java";
System.out.println(strA.equals(strB)); //false
System.out.println(strA.equalsIgnoreCase(strB)); //true
// 注意:
System.out.println("abc一123".equalsIgnoreCase("abc壹123")); // false
}
String中与获取相关的常用方法:
String当中与获取相关的常用方法有:
public int length():获取字符串当中含有的字符个数,拿到字符串长度。
public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。
public char charAt(int index):获取指定索引位置的单个字符。(索引从0开始。)
public int indexOf(String str):查找参数字符串在本字符串当中首次出现的索引位置,
如果没有返回-1。
public class Demo02StringGet {
public static void main(String[] args) {
// 获取字符串的长度
int length = "12345678".length();
System.out.println("字符串的长度是:" + length);
// 拼接字符串
String str1 = "Hello ";
String str2 = "World";
String str3 = str1.concat(str2);
System.out.println(str1); // Hello
System.out.println(str2); // World
System.out.println(str3); // Hello World
System.out.println("==============");
// 获取指定索引位置的单个字符
char ch = "Hello".charAt(1);
System.out.println("在1号索引位置的字符是:" + ch);//e
System.out.println("==============");
// 查找参数字符串在本来字符串当中出现的第一次索引位置
// 如果根本没有,返回-1值
String original = "HelloWorldHelloWorld";
int index = original.indexOf("llo");
System.out.println("第一次索引值是:" + index); //
System.out.println("HelloWorld".indexOf("abc")); //
}
}
String中字符串的截取方法:
/*
字符串的截取方法:
public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。
public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。
*/
public class Demo03Substring {
public static void main(String[] args) {
String str1 = "HelloWorld";
String str2 = str1.substring(5);
System.out.println(str1); // HelloWorld
System.out.println(str2); //World
System.out.println("================");
String str3 = str1.substring(4, 7);
System.out.println(str3); // oWo
System.out.println("================");
// 下面这种写法,原字符串的内容改变了吗?
String strA = "Hello";
System.out.println(strA); // Hello
strA = "Java";
System.out.println(strA); // Java
}
}
String中与转换相关的常用方法:
/*
String当中与转换相关的常用方法有:
public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
替换第一个可用replaceFirst
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。
*/
public class Demo04StringConvert {
public static void main(String[] args) {
// 转换成为字符数组
char[] chars = "Hello".toCharArray();
System.out.println(chars[0]); // H
System.out.println(chars.length); // 5
System.out.println("==============");
// 转换成为字节数组
byte[] bytes = "abc".getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);
}
System.out.println("==============");
//
// 字符串的内容替换
String str1 = "How do you do?";
String str2 = str1.replace("o", "*");
System.out.println(str1); //
System.out.println(str2); //
System.out.println("==============");
String lang1 = "会不会玩儿呀!你大爷的!你大爷的!你大爷的!!!";
String lang2 = lang1.replace("你大爷的", "****");
System.out.println(lang2); // 会不会玩儿呀!****!****!****!!!
}
}
String中分割字符串的方法:
/*
分割字符串的方法:
public String[] split(String regex):按照参数的规则,将字符串切分成为若干部分。
注意事项:
split方法的参数其实是一个“正则表达式”,今后学习。
今天要注意:如果按照英文句点“.”进行切分,必须写"\\."(两个反斜杠)
*/
public class Demo05StringSplit {
public static void main(String[] args) {
String str1 = "aaa,bbb,ccc";
String[] array1 = str1.split(",");
for (int i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
System.out.println("===============");
String str2 = "aaa bbb ccc";
String[] array2 = str2.split(" ");
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
System.out.println("===============");
String str3 = "XXX.YYY.ZZZ";
String[] array3 = str3.split("\\.");
System.out.println(array3.length); //
for (int i = 0; i < array3.length; i++) {
System.out.println(array3[i]);
}
}
}
小练习
- 题目:
定义一个方法,把数组{1,2,3}按照指定格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
分析:
1. 首先准备一个int[]数组,内容是:1、2、3
2. 定义一个方法,用来将数组变成字符串
三要素
返回值类型:String
方法名称:fromArrayToString
参数列表:int[]
3. 格式:[word1#word2#word3]
用到:for循环、字符串拼接、每个数组元素之前都有一个word字样、分隔使用的是#、区分一下是不是最后一个
4. 调用方法,得到返回值,并打印结果字符串
*/
public class Demo06StringPractise {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
String result = fromArrayToString(array);
System.out.println(result);//[word1#word2#word3#word4]
}
public static String fromArrayToString(int[] array) {
String str = "[";
for (int i = 0; i < array.length; i++) {
if (i == array.length - 1) {
str += "word" + array[i] + "]";
} else {
str += "word" + array[i] + "#";
}
}
return str;
}
}
- 题目:
键盘输入一个字符串,并且统计其中各种字符出现的次数。
种类有:大写字母、小写字母、数字、其他
思路:
1.Scanner next()
2.int[] arr :0号元素代表大写字母出现的次数,1号元素代表小写字母出现的次数,
2号元素代表数字出现的次数,3号元素代表其他字符出现的次数
3.字符串转字符数组 toCharArray(),char[] cArr = s.toCharArray();
4.遍历数组,判断并记录次数
*/
public class Demo07StringCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
char[] cArr = s.toCharArray();
int[] count = new int[4];
for (char c : cArr) {
if (c>='A' && c<='Z' ) {
count[0]++;
}else if (c>='a' && c<='z') {
count[1]++;
}else if (c>=48 && c<='9') {
count[2]++;
}else {
count[3]++;
}
}
System.out.println("大写字母:"+count[0]);
System.out.println("小写字母:"+count[1]);
System.out.println("数字:"+count[2]);
System.out.println("其他字符:"+count[3]);
}
}
String中 == 的判别:
/*
* ==的判别:
* 基本数据类型:直接判断值是否相等
* 引用数据类型:判断两个对象的地址是否相等
*/
public class Test {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println(s1 == s2);// true/false
System.out.println(s1 == s3);// false
System.out.println(s2 == s3);// false
System.out.println(s1.equals("abd"));
}
}
相关练习题
-
数组和集合有什么区别?
-
编写程序将String类型字符串”I hate life”改为”I love life
-
计算”na”在”na gei wo banana ”中出现的次数。
-
编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,
如:“To be or not to be",将变成"oT eb ro ton ot eb."。
- 数组和集合有什么区别?
集合和数组都是Java中的容器。
区别
数组特点:大小固定,只能存储相同数据类型的数据
集合特点:大小可动态扩展,可以存储各种类型的数据
- 编写程序将String类型字符串”I hate life”改为”I love life
public class q2_Test {
public static void main(String[] args) {
String s = "I hate life";
System.out.println(s.replace("hate", "love"));
}
}
- 计算”na”在”na gei wo banana ”中出现的次数。
package com.zcl.homework.D07;
public class q3_Test {
public static void main(String[] args) {
String s = "na gei wo banana";
char[] arr1 = s.toCharArray();
int a = 0;
for (int i = 0; i < arr1.length-1; i++) {
if (arr1[i] == 'n' && arr1[i+1] == 'a') {
a++;
}
}
System.out.println("“na”在“na gei wo banana ”中出现的次数为:"+a);
another();
}
public static void another() {
String s = "na gei wo banana";
int count = 0;
while (s.indexOf("na") != -1) {
s = s.replaceFirst("na", " ");
count++;
}
System.out.println(count);
}
}
- 编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,
如:“To be or not to be",将变成"oT eb ro ton ot eb."。
package com.zcl.homework.D07;
import java.util.ArrayList;
public class q4_Test {
public static void main(String[] args) {
String s = "To be or not to be";
String[] arr = s.split(" ");
char[] arr2 = {};
String str = new String();
for (int i = 0; i < arr.length; i++) {
arr2 = arr[i].toCharArray();
int min = 0;
int max = arr2.length-1;
while (min < max) {
char temp = arr2[min];
arr2[min] = arr2[max];
arr2[max] = temp;
str += new String(arr2) + " ";
min++;
max--;
}
}
System.out.print(str);
}
}