一.常用类
1.String类和StringBuffer的基本功能
String的描述以及特点:
String类代表字符串,Java中所有的字符串都被实现为此类的实例,
特点:字符串在被创建之后都是不可变的.
1.1构造函数
public String() //无参构造方法
public String(byte[] bytes)//将字节数组构造成字符串(解码)
public String(char[] chs)//将字符数组构造成字符串'
public String(String orginal)//将字符串常量构造字符串对象
public class StringTest {
public static void main(String[] args) {
//无参构造
String s1 = new String();
System.out.println("s1:"+s1);
//创建字节数组
byte [] arr = {97,98,99,100,103,102};
//字节数组构造成字符串
String s2 = new String(arr);
System.out.println("s2:"+s2);
//创建字节数组
char [] arr2 = {'h','e','l','l','l'};
//将字节数组构造成字符串
String s3 = new String(arr2);
System.out.println("s3:"+s3);
}
}
输出结果:
1.2String类的获取功能
public char charAt(int index)//获取指定索引处出的字符
public String[] spilt(String regex)//将字符串通过特定的分割符号进行拆分,获取到字符串数组
public String concat(String str)//字符串拼接功能str进行拼接
public int length() //获取字符串长度
public int indexOf(int ch)//查询当前字符串中某个字符第一次出现索引值
String substring(int beginIndex) :字符串截取功能 (重要)
默认从beginIndex起始索引截取到末尾
public String substring(int beginIndex,int endIndex):
从指定位置开始截取到指定位置结束(包前不包后)包含beginIndex位置,不包含endIndex位置,包含到endIndex-1
public class StringTest2 {
public static void main(String[] args) {
//创建一个字符串
String s = "HelloWorld";
//获取制定索引处的字符
System.out.println(s.charAt(5));
//字符串拼接
String s2 = s.concat("JavaEE");
String s3 = s2.concat("JavaSE");
System.out.println(s3);
//获取字符串的长度
System.out.println(s.length());
//查询当前字符串中某个字符第一次出现的索引值
s.indexOf("JavaEE");
//将字符串分割,得到字符串数组
s = "Java-Php-c++-c#-c-Python-Go";
//通过-将字符串分割
String [] s1 = s.split("-");
//遍历数组
for(int i = 0;i < s1.length;i++){
System.out.println(s1[i]+" ");
}
System.out.println();
//字符串截取从指定数字到末尾String substring(int beginIndex)
String substring = s.substring(5);
System.out.println(substring);
//从指定数字到指定数字(包前不包后)
String substring1 = s.substring(0, 5);
System.out.println(substring1);
}
}
输出结果:
1.3String的转换功能
public char[] toCharArry() //将字符串转换成字符数组
public byte[] getBytes() //使用平台的默认字符集进行编码,将字符串转换成字节数组
public static String valueOf(int/boolean/double/float/Object...)//万能方法:将任何数据类型转换成字符串
public String toLowerCase()//将字符串转换成小写
public String toUpperCase()//将字符串中的每个字符转换成大写
public class StringTest3 {
public static void main(String[] args) {
//创建一个字符串
String s = "Hello,World JavaEE";
//将字符串转换为字符数组
char[] chars = s.toCharArray();
//遍历
printArray(chars);
System.out.println();
//讲字符串转换为字节数组
byte[] bytes = s.getBytes();
//遍历
printArray(bytes);
System.out.println();
//将字符串中每个单词转换为小写
String s1 = s.toLowerCase();
String s2 = s.toUpperCase();
System.out.println(s1);
System.out.println(s2);
}
//遍历字符数组
public static void printArray(char [] arr){
for (int i = 0;i < arr.length;i++){
System.out.print(arr[i]+" ");
}
}
//遍历字符数组
public static void printArray(byte [] arr){
for (int i = 0;i < arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
输出结果:
1.4String的其他功能
替换功能replace;
去除字符串中的空格:trim;
将两个字符串按照字典顺序进行:
int compareTo(String anotherString)
public class StringTest4 {
public static void main(String[] args) {
//创建一个字符串
String s = " H e ll o,J a va ";
//替换功能
//replace(char oldChar,char newChar)使用新字符去替换旧的字符
String replace = s.replace('l', 'o');
System.out.println(replace);
//可以用替换去掉字符串中的空格
String replace1 = s.replace(" ", "");
System.out.println(replace1);
//去除字符串前面和后面的空格
String trim = s.trim();
System.out.println(trim);
//按照字典顺序比较
String s1 = "Java,Welcome";
int i = s.compareTo(s1);
System.out.println(i);
}
}
输出结果:
1.5什么是StringBuffer和String的区别以及常用方法
StringBuffer:简称"字符串缓冲区",线程安全的,而且可变的字符序列
String和StringBuffer的区别:
String:为字符串常量,一旦被定义之后无法修改,不可变的字符序列
StringBuffer:是可变的字符序列,线程安全,同步,但是执行效率低
1.5.1StringBuffer的常用方法
构造方法:
StringBuffer的构造方法
StringBuffer();无参构造方法 :使用居多
StringBuffer(int capacity):指定容量大小的字符串缓冲区
StringBuffer(String str) :指定缓冲区的具体内容str,容量大小=16个默认容量+当前字符串长度
public int length()获取字符缓冲区中的长度
public int capacity():获取字符串缓冲区中的容量大小
其他方法:
StringBuffer的反转:reverse()
StringBuffer的添加:
append(任何数据类型)/insert插入相关的方法...
删除:deletCharAt(int index):删除指定索引处的字符
delete(int startIndex,int endIndex)删除从指定位置开始到指定位置结束...(包前不包后)
public class StringBuffer1 {
public static void main(String[] args) {
//无参构造方法
StringBuffer s = new StringBuffer();
//指定容量大小的字符串缓冲区
StringBuffer s1 = new StringBuffer(20);
//指定字符串缓冲区的内容
StringBuffer s2 = new StringBuffer("Hello,world");
//获取缓冲区的长度
System.out.println(s.length());
System.out.println(s1.length());
System.out.println(s2.length());
//获取字符串缓冲区中的容量大小
System.out.println(s.capacity());
System.out.println(s1.capacity());
System.out.println(s2.capacity());
//StringBuffer的反转
System.out.println(s2.reverse());
System.out.println(s2.reverse());
//StringBuffer的添加
System.out.println(s2.append("JavaEE"));
//删除指定位置索引处的字符
System.out.println(s2.deleteCharAt(5));
//删除指定索引的一段字符串
System.out.println(s2.delete(5,10));
}
}
2.Object类的常用方法
1.public String toString():
返回对象的字符串表示形式
源码:
public String toString(){
return this.getClass().getName()+"@"+Integer.toHexString(this.hashCode()) ;
}
2.public boolean equals(Object obj):
源码:
public boolean equals(Object anotherObj){
return this == anotherObj;
}
指示一些其他对象是否等于此。
Object是所有类的子类,需要重写toString()方法和equals()方法
public class Object {
public static void main(String[] args) {
//字符串比较,在java中,有两种比较的方法:==和equals
//==用来进行数值的比较,不能进行对字符串的比较,字符串比较需要用到equals
//==:连接的是引用数据类型,比较的是引用数据类型的地址值是否相同
//equals:默认比较的是地址值是否相同,建议子类重写equals方法,比较他们内容是否相同(成员信息是否相同)
String s = new String("Hello");
String s2 = new String("Hello");
String s3 = new String("hello");
//==比较
System.out.println(s == s2);
System.out.println(s == s3);
//equals比较
System.out.println(s.equals(s2));
System.out.println(s.equals(s3));
}
}
输出结果:
3.Date类.System功能.Math类.Random类.
3.1Date类:
在前后端交互中,前端传来的数据都是String类型,而后端中数据库中存储的和操作的数据是Date类型,所以就需要数据类型转换.
如何转化:
DateFormat是日期/时间格式化子类的抽象类,它以语言无关的方式格式化和分析日期或时间。但是它是一个抽象类. 抽象类不能实例化,它提供了更具体的子类SimpleDateFormat进行操作!
public class DateDemo2 {
public static void main(String[] args) throws ParseException {
//Date---->String 日期文本
//创建日期对象:表示当前系统时间
Date date = new Date() ;
//创建SimpleDateFormat对象:中间桥梁(格式化/解析 工具)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
// public final String format(Date date)
String dateStr = sdf.format(date);
System.out.println(dateStr) ;
System.out.println("------------------------------------------") ;
//String文本------->Date日期格式
String sourc = "2008-5-12" ;
//当前的SimpleDateFormat的模式必须和字符串文本格式对应!,否则解析出问题了
//创建SimpleDateFormat对象
// SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日" ) ;
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd" ) ;
//public Date parse(String source) throws ParseException:
Date date2 = sdf2.parse(sourc);
System.out.println(date2) ;//Mon May 12 00:00:00 CST 2008
}
}
运行结果:
3.2 System
System类:不能实例化
提供一些标准输入流,
静态字段(常量):
public static final InputSteam in ;
public static final PrintStream out ;
静态功能:
public static void gc() //手动开启垃圾回收器
public static void exit(int status)//:参数为0,正常终止JVM
public static void arraycopy(Object src,int srcPos,Object dest,int destPos, int length)
复制数组
public static long currentTimeMillis()//:计算当前系统时间毫秒值
public class SystemDemo2 {
public static void main(String[] args) {
//创建Person类对象
Person p = new Person("高圆圆" ,42) ;
System.out.println(p) ;
p = null ;
System.gc() ;//手动开启垃圾回收器
}
}
二.集合
1.集合的概述:什么是集合?有什么用?
数组其实就是一个集合。集合实际上就是一个容器。可以来容纳其它类型的数据。
集合为什么在开发中使用较多?
集合是一个容器,是一个载体,可以一次容纳多个对象。在实际开发中,假设连接
数据库,数据库当中有10条记录,那么假设把这10条记录查询出来,在java程序中
会将10条数据封装成10个java对象,然后将10个java对象放到某一个集合当中,
将集合传到前端,然后遍历集合,将一个数据一个数据展现出来。
2.集合的继承结构图:
2.1Collection集合:
2.2Map集合:
3.Collection集合的高级功能:
boolean addAll(Collection c):添加一个集合中的所有元素
boolean containsAll(Collection c):包含一个集合的所有元素
boolean removeAll(Collection c):结论:删除一个集合中包含另一个集合中的某个元素,就算删除,返回true
3.1对于集合的添加
public class CollectionTest1 {
public static void main(String[] args) {
//创建一个集合
//因为Collection是一个结构,学过面向对象的都知道,接口不能new对象,需要创建接口的子实现类
Collection c1 = new ArrayList<>();
//使用add()先ArrayList集合中添加元素
c1.add("hello");
c1.add("world");
c1.add("JavaEE");
c1.add("这个世界");
//输出
System.out.println(c1);
}
}
3.2集合的遍历:
Iterator<E> iterator():迭代器:集合专有遍历方式
Iterator:接口
boolean hasNext() 判断是否有下一个可以迭代的元素 (判断功能)
Object next():获取下一个可以迭代的元素 (获取功能)
public class Student {
private String name;
private String address;
private int age;
public Student() {
}
public Student(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
//test类
public class CollectionTest2 {
public static void main(String[] args) {
//集合的遍历,先创建集合,添加元素并且遍历
Collection c = new ArrayList();
//添加元素
Student s1 = new Student("盖伦","德玛西亚",20);
Student s2 = new Student("光辉","德玛西亚",18);
Student s3 = new Student("德莱厄斯","诺克萨斯",25);
Student s4 = new Student("德莱文","诺克萨斯",24);
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
//遍历集合中的元素
//获取迭代器,接口多态,创建迭代器
Iterator it = c.iterator();
while(it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName()+"----"+s.getAddress()+"----"+s.getAge());
}
}
}
输出结果:
3.3.List集合:
List集合是Collection的子接口,有Collection的大多数功能,但是也有字节的特有功能.
List接口特有功能:
void add(int index, Object element):在指定位置处添加一个新的元素
Object remove(int index):删除指定位置处的元素
E set(int index, Object element):修改指定位置处的元素内容
Object get(int index):获取指定位置处的元素
ListIterator<E> listIterator():列表迭代器
public class ListTest {
public static void main(String[] args) {
//创建List集合:
List l = new ArrayList();
//向集合中添加元素
l.add("hello");
l.add("world");
l.add("JavaEE");
//向指定的位置添加元素
l.add(2,"无名之辈");
System.out.println("----------------------------");
//删除指定位置的元素
Object remove = l.remove(0);
System.out.println(remove);
System.out.println("-------------------------------");
//修改指定位置处的元素内容
System.out.println(l.set(1, "世界"));
System.out.println("-------------------------------");
//获取指定位置的元素
System.out.println(l.get(2));
System.out.println(l.get(1));
System.out.println("-------------------------------");
//List集合的遍历方式:
//第一种:通过Collection的toArray方法.将集合转化为数组,通过for循环遍历数组
Object[] objects = l.toArray();
for (int i = 0; i < objects.length; i++){
System.out.println(objects[i]);
}
System.out.println("-------------------------------");
//第二种,通过Collection的迭代器
Iterator it = l.iterator();
while (it.hasNext()){
String name = (String) it.next();
System.out.println(name);
}
}
}
3.4.JDK5的新特性:
for增强作用:替换迭代器,简化书写,
使用:
for(数据类型 数据名:集合对象名称){
输出遍历名;
}
public class League {
private String name;
private String country;
public League() {
}
public League(String name, String country) {
this.name = name;
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "League{" +
"name='" + name + '\'' +
", country='" + country + '\'' +
'}';
}
}
//测试类
public class ForEachTest {
public static void main(String[] args) {
//创建一个集合
Collection<League>leagues = new ArrayList();
//给集合中添加对象
League league1 = new League("皇子","德玛西亚");
League league2 = new League("大树","暗影岛");
League league3 = new League("奎因","德玛西亚");
League league4 = new League("寒冰","弗雷尔卓德");
leagues.add(league1);
leagues.add(league2);
leagues.add(league3);
leagues.add(league4);
//集合的遍历
//1.使用迭代器
Iterator it = leagues.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("-------------------------------------------------");
//2.使用增强for循环
for( League s:leagues){
System.out.println(s);
}
}
}
输出结果:
3.5.泛型
什么是泛型?有什么用?
泛型的使用: <引用数据类型>
集合对象的创建同时明确数据类型,并且将运行时期异常提前到了编译时期(模拟数组定义)
泛型的好处:
1)提高程序安全性
2)解决黄色警告线
3)使用集合的迭代器避免强转类型强转类型转换
//创建集合
public class Generic{
public static void main(String[] args){
//创建一个ArrayList集合中间使用泛型标记存放String类型的数据,
List<String> list = new ArrayList<>();
//给集合中添加元素
list.add("欢迎来到德莱联盟!");
list.add("亲爱的,你爱我么?有多爱,比昨天多一点,比明天少一点!");
list.add("犯我德邦者,虽远必诛!");
//使用迭代器遍历集合
Iterator it = list.iterator();
while(it.hasNext()){
String s = (String) it.next();
System.out.println(s);
}
}
}
3.6.ArrayList集合
* 构造方法:
* public ArrayList():构造一个初始容量为十的空列表。
* public ArrayList(int initialCapacity):指定容量大小
*/
public class ArrayListTest {
public static void main(String[] args) {
//创建ArrayList集合对象
// ArrayList<String> arrayList = new ArrayList<>() ;
//无参构造创建:十的空列表。
//public ArrayList(int initialCapacity):指定容量大小
ArrayList<String> arrayList = new ArrayList<>(20) ;
arrayList.add("hello") ;
arrayList.add("world") ;
arrayList.add("java") ;
}
}
3.7.Vector
Vector集合:在List集合中最明显的特点:线程安全
目前为止:线程安全的类(多线程中使用)
StringBuffer/Vector/
线程安全的方法:Collections:针对集合操作工具类
public static <T> List<T> synchronizedList(List<T> list):保证列表同步(安全方法)
特有功能:
特有功能:
public void addElement(Object obj):添加元素
public boolean removeElement(Object obj):直接从Vector集合中删除指定的元素
public Object elementAt(int index):通过指定的索引值获取元素------类似于List集合中get(int index)
public Enumeration<Object> elements():(特有迭代器)获取Vector集合中的枚举组件接口 boolean hasMoreElements() ---->类似于boolean hasNext() 判断是下一个遍历的元素
Object nextElement() ---类似于 Object next() 获取下一个元素
public class VectorTest {
public static void main(String[] args) {
//创建Vector集合
Vector<String>v = new Vector();
//给集合中添加元素
v.add("饺子");
v.add("泡馍");
v.add("饸络");
v.add("粉蒸肉");
v.add("小酥肉");
System.out.println(v);
//从指定的位置删除元素
System.out.println(v.removeElement("饸络"));
System.out.println(v);
System.out.println("-----------------------------------------");
//通过指定的索引值获取元素
System.out.println(v.elementAt(3));
System.out.println("------------------------------------------");
//特有的迭代器
Enumeration<String> en = v.elements();
while (en.hasMoreElements()) {
String s = en.nextElement();
System.out.println(s);
}
}
}
输出结果:
3.8.LinkedList
LinkedList:不同步,线程不安全,执行效率高; 数据结构是:链表
特有功能:
public void addFirst(Object e):在链表开头插入元素
public void addLast(Object e):将元素追加到链表的末尾
public Object getFirst():获取链表的第一个元素
public Object getLast():获取链表的最后一个元素
public Object removeFirst():删除链表第一个元素并获取第一个元素
public Object removeLast():删除链表最后一个元素并获取
public class LinkedListTest {
public static void main(String[] args) {
//创建LinkedList集合
LinkedList <String> lkd = new LinkedList();
//给集合中添加元素
//addFirst()将元素添加到集合中的第一个元素
lkd.addFirst("h");
lkd.addFirst("e");
lkd.addFirst("l");
lkd.addFirst("l");
lkd.addFirst("o");
//addLast():将元素添加到集合的末尾,
lkd.addLast("j");
lkd.addLast("a");
lkd.addLast("v");
lkd.addLast("a");
System.out.println(lkd);
System.out.println("-------------------------------------------");
//获取集合中的第一个元素
String first = lkd.getFirst();
System.out.println(first);
System.out.println("--------------------------------------------");
//获取集合中的最后一个元素
String last = lkd.getLast();
System.out.println(last);
System.out.println("----------------------------------------------");
//删除链表第一个元素并返回
String remove = lkd.removeFirst();
System.out.println(remove);
System.out.println("---------------------------------------------");
//删除链表最后一个元素并返回
String last1 = lkd.removeLast();
System.out.println(last1);
}
}
输出结果:
3.9,HashSet
set集合:无序,能保证元素唯一
代表HashSet子实现类
底层一个HashMap的实例,保证元素唯一(底层哈希表,和HashMap有关系),不能保证迭代顺序恒久不变!
为什么Set集合能保证元素唯一:
hashSet集合的添加功能,add方法:间接依赖于的HashMap的put方法----->底层依赖于hashCode()和equals()方法
首先,要比较当前存储String类型数据的哈希码值是否相同,如果相同,
比较内容是否一样,调用equals()方法,String类型已经重写了Object,比较内容!
HashSet<String>,并遍历
public class HashSetTest {
public static void main(String[] args) {
//创建HashMap集合
Set<String>s = new HashSet<>();
//给集合中添加元素
s.add("hello");
s.add("world");
s.add("hello");
s.add("JavaEE");
s.add("PHP");
s.add("Python");
s.add("C#");
s.add("Python");
s.add("PHP");
s.add("Java");
System.out.println(s);
}
}
输出结果:
3.9.1.HashSet的排序:
1)自然排序:通过实现Comparbale接口;
需求:录入几个学生的英语成绩和数学成绩,按总分从高到低排序:
public class Student implements Comparable<Student>{
private String name;
private int id;
private int math;
private int english;
public Student() {
}
public Student(String name, int id, int math, int english) {
this.name = name;
this.id = id;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getNum(){
return math+english;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", math=" + math +
", english=" + english +
'}';
}
@Override
public int compareTo(Student student) {
//主要条件,总分从高到低排序
int num = student.getNum() - this.getNum();
//次要条件:如果总分一样,按数学从高到低
int num2 = (num == 0)?(student.getMath() - this.getMath()):num;
//如果总分一样,数学一样,那就算英语也一样
int num3 = (num2 == 0)?(student.getMath() - this.getMath()):num;
return num3;
}
}
//测试类
public class HashSetTest1 {
public static void main(String[] args) {
//创建HashSet集合
Set <Student> s = new HashSet<Student>();
//创建学生对象并添加
Student student = new Student("张三",1801,80,70);
Student student1 = new Student("李四",1802,60,100);
Student student2 = new Student("王五",1803,88,60);
Student student3 = new Student("赵六",1804,90,90);
Student student4 = new Student("冯七",1805,60,80);
//将对象添加到集合中
s.add(student);
s.add(student1);
s.add(student2);
s.add(student3);
s.add(student4);
System.out.println(s);
System.out.println("------------------------------------------");
//增强for循环
for(Student students : s){
System.out.println(students);
}
}
}
输出结果: