集合
一、ArrayList集合
1.集合类的特点
提供一个存储空间可以改变的存储模型,存储的数据容量可以进行改变
ArrayList<E> //在 java utill 包下
//可以调整大小的数组实现
//<E>是一种特殊的数据类型,即泛型
2.ArrayList的创建和添加
public class ArrayListDemo01 {
public static void main(String[] args) {
//创建一个空集合对象
//public ArrayList();
ArrayList<String> arrayList=new ArrayList<>();
System.out.println(arrayList);//输出为 []
//将指定元素添加到集合末尾
//public boolean add(E e);
arrayList.add("hello");
arrayList.add("world");
System.out.println(arrayList);//输出为 [hello, world]
//在指定位置插入元素
//public void add(int index,E element);
arrayList.add(1,"wao");
System.out.println(arrayList);//输出为 [hello, wao, world]
}
}
3.ArrayList的删除
public boolean remove(Object o);-----返回删除是否成功
public E remove(int index);-----返回被删除的元素
public static void main(String[] args) {
//创建
ArrayList<String> arrayList=new ArrayList<>();
//添值
arrayList.add("hello");
arrayList.add("world");
arrayList.add("wao");
arrayList.add("fine");
System.out.println(arrayList);//输出[hello, world, wao, fine]
//删除指定元素 public boolean remove(Object o);
arrayList.remove("wao");
System.out.println(arrayList);//输出[hello, world, fine]
//删除指定位置的元素 public E remove(int index);
arrayList.remove(1);
System.out.println(arrayList);//输出[hello, fine]
}
4.ArrayList的修改
public E set(int index,E element);-----返回被修改的元素
public class ArrayListDemo03 {
public static void main(String[] args) {
//创建
ArrayList<String> arrayList=new ArrayList<>();
//添值
arrayList.add("hello");
arrayList.add("world");
arrayList.add("wao");
arrayList.add("fine");
System.out.println(arrayList);//输出[hello, world, wao, fine]
//修改指定位置的元素 public E set(int index,E element);
arrayList.set(1,"java");
System.out.println(arrayList);//输出[hello, java, wao, fine]
}
}
5.ArrayList的获取元素
public E get(int index);-----返回被获取的元素
public class ArrayListDemo04 {
public static void main(String[] args) {
//创建
ArrayList<String> arrayList=new ArrayList<>();
//添值
arrayList.add("hello");
arrayList.add("world");
arrayList.add("wao");
arrayList.add("fine");
System.out.println(arrayList);//输出[hello, world, wao, fine]
//获取指定元素 public E get(int index);
System.out.println(arrayList.get(0));//输出hello
System.out.println(arrayList.get(1));//输出world
System.out.println(arrayList.get(2));//输出wao
}
}
6.ArrayList的获取集合元素的个数
public int size();-----返回集合中元素的个数
public class ArrayListDemo05 {
public static void main(String[] args) {
//创建
ArrayList<String> arrayList=new ArrayList<>();
//添值
arrayList.add("hello");
arrayList.add("world");
arrayList.add("wao");
arrayList.add("fine");
System.out.println(arrayList);//输出[hello, world, wao, fine]
//获取集合中元素的个数 public int size();
System.out.println(arrayList.size());//输出4
}
}
7.集合的遍历
public class ArrayListDemo06 {
public static void main(String[] args) {
//创建
ArrayList<String> arrayList=new ArrayList<>();
//添值
arrayList.add("hello");
arrayList.add("world");
arrayList.add("wao");
arrayList.add("fine");
System.out.println(arrayList);//输出[hello, world, wao, fine]
//集合对象的遍历
for (int i=0;i<arrayList.size();i++){
String a = arrayList.get(i);
System.out.println(a);
/*
输出
hello
world
wao
fine
*/
}
}
}
二、集合
1.1 集合的分类
集合分为Collection(单列集合)和Map(双列集合);Collection中包含List(可重复)和Set(不可重复)
1.2 Collection的创建(多态)
//创建集合对象
Collection<String> c = new ArrayList<String>();
1.3 Collection的常用方法
(1)添加元素
//添加集合元素 boolean add(E e);
c.add("hello"); //输出true
c.add("world"); //输出true
c.add("world"); //输出true
System.out.println(c);//输出[hello, world, world]
(2)删除某个元素
//boolean remove(Object o);
c.remove("hello");
(3)清空集合中的元素
//void clear();
c.clear();//输出[]
(4)判断集合是否为空
//boolean isEmpty();
c.isEmpty();
(5)集合长度
//int size();
c.size();
1.4 Collection集合的遍历
通过接口Iterator迭代器,是集合的专用遍历方式
//通过Iterator返回iterator()方法
Iterator<String> iterator = c.iterator();
//判断是否有下一个元素
iterator.hasNext();
//输出元素
iterator.next();
public class CollectionDemo02 {
public static void main(String[] args) {
//创建集合对象
Collection<String> c = new ArrayList<String>();
//添加集合对象
c.add("hello");
c.add("world"); //输出true
c.add("java"); //输出true
System.out.println(c);//输出[hello, world, java]
//通过Iterator返回iterator()方法
Iterator<String> iterator = c.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
/*
输出
hello
world
java
*/
}
}
2.1 List特点
List是有序集合(存储和取出的元素顺序一致);列表中允许出现重复元素
public class ListDemo01 {
public static void main(String[] args) {
//创建List对象
List<String> list=new ArrayList<String>();
//添加元素
list.add("hello");
list.add("world");
list.add("java");
list.add("world");
list.add("hello");
System.out.println(list);//[hello, world, java, world, hello]
//迭代器遍历
Iterator<String> it=list.listIterator();
while (it.hasNext()){
System.out.println(it.next());
}
/*
hello
world
java
world
hello
*/
}
}
2.2 List的特有方法
public class ListDemo02 {
public static void main(String[] args) {
//创建List对象
List<String> list=new ArrayList<String>();
//添加元素
list.add("hello");
list.add("world");
list.add("java");
System.out.println(list);//[hello, world, java]
//删除元素
list.remove(0);
System.out.println(list);//[world, java]
//修改元素
list.set(0,"hello");
System.out.println(list);//[hello, java]
//返回指定元素
System.out.println(list.get(0));//hello
//用for循环进行遍历
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
2.3 ListIterator列表迭代器
1.可以沿任一方向遍历列表
2.在遍历期间可以修改列表
3.可以获取列表中迭代器的当前位置
public class ListDemo03 {
public static void main(String[] args) {
//创建List对象
List<String> list=new ArrayList<String>();
//添加元素
list.add("hello");
list.add("world");
list.add("java");
//列表迭代器
ListIterator<String> listIterator = list.listIterator();
//正序遍历
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
//逆序遍历
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
//在迭代过程中添加元素
while (listIterator.hasNext()){
String s = listIterator.next();
if(s.equals("world")){
listIterator.add("wao");
}
}
System.out.println(list);//[hello, world, wao, java]
}
}
2.4 利用增强for循环遍历(本质上是Iterator)
public class ListDemo04 {
public static void main(String[] args) {
//创建List对象
List<String> list = new ArrayList<String>();
//添加元素
list.add("hello");
list.add("world");
list.add("java");
//增强for循环遍历
for (String s:list){
System.out.println(s);
}
}
}
2.5 List集合子类特点
1.ArrayList:底层数据结构是数组,查询快,增删慢
2.LinkedList:底层数据结构是链表,查询慢,增删快
2.6 LinkedList的特有方法
//创建LinkedList对象
LinkedList<String> linkedList = new LinkedList<String>();
//在列表开头插入元素
linkedList.addFirst("hello");
//在列表末尾插入元素
linkedList.addLast("hello");
//返回列表开头元素
linkedList.getFirst();
//返回列表末尾元素
linkedList.getLast();
//删除列表开头元素
linkedList.removeFirst();
//删除列表末尾元素
linkedList.removeLast();
3.1 Set集合的特点
1.不包含重复元素的集合
2.没有带索引的方法,所以不能使用普通的for循环遍历
public class SetListDemo01 {
public static void main(String[] args) {
//HashSet对顺序没有保证
Set<String> set = new HashSet<>();
set.add("hello");
set.add("world");
set.add("java");
set.add("wao");
for (String a:set){
System.out.println(a);
}
/*输出
world
java
wao
hello
*/
}
}
3.2 哈希值
1.哈希值是JDK根据对象的地址或字符串或数字算出来的int类型的数值
2.同一对象多次调用的hashCode()方法返回的哈希值是相同的
3.默认情况下,不同对象调用的hashCode()方法返回的哈希值是不同的;而重写hashCode()方法可以实现不同对象的哈希值相同
3.3 HashSet
1.存储和取出元素顺序不一致
2.没有索引方法,所以不能使用普通for循环进行遍历
3.是Set集合,不包含重复元素
//创建
HashSet<String> hashSet=new HashSet<String>();
//遍历
for (String a:hashSet){
System.out.println(a);
}
3.4 LinkedHashSet
1.通过哈希表和链表实现Set接口
2.元素的存储和取出顺序是一致的
3.没有重复元素
3.5 TreeSet
1.元素有序,按照一定的规则进行排序,具体排序方法取决于构造方法
TreeSet():根据元素自然排序(从小到大)
TreeSet(Comparator comparator):根据指定的比较器进行排序
2.不能使用普通for循环遍历
3.没有重复元素
public class TreeSetDemo01 {
public static void main(String[] args) {
//创建
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(10);
ts.add(50);
ts.add(40);
ts.add(60);
ts.add(30);
//遍历
for (Integer a : ts){
System.out.println(a);
}
/*
输出
10
30
40
50
60
*/
}
}
4.自然排序,使用Compareable接口,并且重写comparableTo(To)方法 ; return 0 不输出 ;return 1 从小到大输出 ;return -1 从大到小输出
//学生类
public class Student implements Comparable<Student>{
String name;
int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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 int compareTo(Student s) {
int num = this.age-s.age;
int num2= num==0?this.name.compareTo(s.name):num;
return num2;
}
}
public class Demo {
public static void main(String[] args) {
//创建集合
TreeSet<Student> st = new TreeSet<Student>();
//创建学生对象
Student s1 = new Student("zhang",15);
Student s2 = new Student("wan",19);
Student s3 = new Student("chen",20);
Student s4 = new Student("lin",15);
st.add(s1);
st.add(s2);
st.add(s3);
st.add(s4);
//遍历集合
for (Student s:st){
System.out.println(s.getName()+","+ s.getAge());
}
}
}
5.比较器排序,使用Comparator
//学生类
public class Student {
String name;
int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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 class TreeSetDemo02 {
public static void main(String[] args) {
//创建集合对象
TreeSet<Student> st = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num=s1.getAge()-s2.getAge();
int num2=num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
//创建学生对象
Student s1 = new Student("wang",20);
Student s2 = new Student("zhang",24);
Student s3 = new Student("lin",26);
Student s4 = new Student("chen",20);
st.add(s1);
st.add(s2);
st.add(s3);
st.add(s4);
//遍历集合
for (Student s:st){
System.out.println(s.getName()+","+ s.getAge());
}
/*
输出
chen,20
wang,20
zhang,24
lin,26
*/
}
}
4.1 Map集合
// Interface Map<K,V>
K:键的类型
V:值的类型
//创建集合对象
Map<String,String> map = new HashMap<String,String>();
4.2 Map集合常用方法
1.添加元素
//添加元素,将指定值与该映射中的指定键相关联,当键相同时,值会替代掉前一个
map.put("206245","zhang");//{206245=zhang}
map.put("206245","wang");//{206245=wang}
2.删除键及对应的值
map.remove("206245");
3.移除所有键及对应的值
map.clear();
4.判断是否包含指定的键
map.containsKey("206245");
5.判断是否包含指定的值
map.containValue("zhang");
6.判断是否为空
map.isEmpty();
7.集合长度(个数)
map.size();
8.获取
map.get(“206245”);//根据键获取值
Set<String> keySet = map.keySet();//获取所有键的集合
for(String k : keySet){
System.out.println(k);
}
Collection<String> values= map.values();//获取所有值的集合
for(String v : values){
System.out.println(v);
}
4.3 Map遍历
//遍历方法1
//获取键
Set<String> keySet = map.keySet();
for (String k : keySet){
String v = map.get(k);//根据键获取值
System.out.println(k+","+v);
}
//遍历方法2
//获取所有键值的集合
Set<Map.Entry<String,String>> entrySet = map.entrySet();
for (Map.Entry<String,String> m : entrySet){
String key = m.getKey();//获得键
String value = m.getValue();//获得值
System.out.println(key+","+value);
}
常用类
一、Object
1.Object 是 Java 类库中的一个特殊类,是所有类的父类;Java 允许把任何类型的对象赋给 Object 类型的变量,当一个类被定义后,如果没有指定继承的父类,那么默认父类就是 Object 类。
2.常用方法:
(1)toString() 方法
toString() 方法返回该对象的字符串,当程序输出一个对象或者把某个对象和字符串进行连接运算时,系统会自动调用该对象的 toString() 方法返回该对象的字符串表示
//定义类
public class Person {
String name;
int age;
//构造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//重写object中的toString()方法
@Override
public String toString() {
return "姓名:"+this.name+" 年龄:"+this.age;
}
}
//主方法
public class Test {
public static void main(String[] args) {
//实例化
Person person = new Person("zhang",18);
System.out.println(person);//打印对象调用toString()方法
}
}
(2)equals()方法
两种比较方法,分别是‘ == ’运算符和equals()方法,‘ == ’是比较两个引用变量是否指向同一个实例,equals() 方法是比较两个对象的内容是否相等
(3)getClass()方法
getClass() 方法返回对象所属的类,是一个 Class 对象;通过 Class 对象可以获取该类的各种信息,包括类名、父类以及它所实现接口的名字等。
二、String
1.String 类可以用来创建和操作字符串
String类对象创建后不能修改
String s1 = " hello" ;//String 直接创建
String s2 = new String(" hello ") ;//String 对象创建
2.String常用方法
(1)获取字符串长度
s1.length();
(2)连接字符串
//concat()
s1.concat(s2);
或
//使用 '+'
s1 + s2 + " ... " ;
(3)获取字符串某一位置字符
//public char charAt(int index)
String str = new String("abcdefg");
char ch = str.charAt(4) ; //ch = e
(4)提取字符串
// public String substring(int beginIndex)
// public String substring(int beginIndex, int endIndex)
String s1 = new String("abcdefghijk");
String s2 = s1.substring(2);//s2 = "cdefghijk" 从2到最后
String s3 = s1.substring(2,5);//s3 = "cde" 从2到4
(5)字符串比较
// public int compareTo(String anotherString) //该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0
// public int compareToIgnore(String anotherString) //与compareTo方法相似,但忽略大小写
// public boolean equals(Object anotherObject) //比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false
// public boolean equalsIgnoreCase(String anotherString) //与equals方法相似,但忽略大小写
String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true
(6)字符串查找
//public int indexOf();
//public int lastIndexOf();
String str = "hello world I am fine";
System.out.println(str.indexOf("o"));// 4
System.out.println(str.indexOf("e",2)); //20 从2(包含2)向后找
System.out.println(str.lastIndexOf("e")); //20
System.out.println(str.lastIndexOf("e",19)); // 1 从19(包含19)向前找
(7)字符串中字符的大小写转换
// public String toLowerCase()
// public String toUpperCase()
String str = new String("abCD");
String str1 = str.toLowerCase();//str1 = "abcd"
String str2 = str.toUpperCase();//str2 = "ABCD"
(8)字符串中字符的替换
// public String replace(char oldChar, char newChar)
// public String replaceFirst(String regex, String replacement)
// public String replaceAll(String regex, String replacement)
String str = "asdzxcasd";
String str1 = str.replace('a','g');//str1 = "gsdzxcgsd" 所有'a'替换为‘g’
String str2 = str.replaceFirst("asd","fgh");//str2 = "fghzxcasd" 遇到的第一个asd替换为fgh
String str3 = str.replaceAll("asd","fgh");//str3 = "fghzxcfgh" 所有的asd替换为fgh
三、StringBuilder
1.StringBuilder对象中的内容是可变的;它和 StringBuffer 之间的最大不同在StringBuilder 的方法不是线程安全的;但 StringBuilder 相较于 StringBuffer 有速度优势
StringBuilder sbr = new StringBuilder();
2.常用方法
// 对象名.length() 序列长度
System.out.println(sbl.length()); // 0
// 对象名.append() 追加到序列
sbl.append("hello");
System.out.println(sbl); // hello
// 输出数字对应的字符
sbl.appendCodePoint(97); //9为‘a’
System.out.println(sbl); // helloa
// 链式编程
sbl.append(1).append("world").append(2);
System.out.println(sbl); // helloa1world2
// 索引是5的位置替换成空格
sbl.setCharAt(5, ' ');
System.out.println(sbl); // hello 1world2
// 指定位置0前插入0
sbl.insert(0, 0);
System.out.println(sbl); // 0hello 1world2
// 删除索引6(包含)至索引14(不包含)的字符串
sbl.delete(6, 14);
System.out.println(sbl); // 0hello
// StringBuilder类型转换成String类型
String s = sbl.toString();
System.out.println(s); // 0hello
---------------------------------------------------
// string转换成StringBuilder
String str = "hello";
StringBuilder sbl = new StringBuilder(str);
System.out.println(sbl); // hello
四、StringBuffer
1.StringBuffer 类的对象后可以随意修改字符串的内容;每个 StringBuffer 类的对象都能够存储指定容量的字符串,如果字符串的长度超过了 StringBuffer 类对象的容量,则该对象的容量会自动扩大
// StringBuffer() 构造一个空的字符串缓冲区,并且初始化为 16 个字符的容量
// StringBuffer(int length) 创建一个空的字符串缓冲区,并且初始化为指定长度 length 的容量
// StringBuffer(String str) 创建一个字符串缓冲区,并将其内容初始化为指定的字符串内容 str,字符串缓冲区的初始容量为 16 加上字符串 str 的长度
2.常用方法
//追加字符串 append(String str)
StringBuffer sbf= new StringBuffer("hello,");
sbf.append("World!"); // 向 StringBuffer 对象追加 字符串
System.out.println(sbf); // Hello,World!
//替换字符 setCharAt(int index, char ch);
StringBuffer sbf = new StringBuffer("hello");
sbf.setCharAt(1,'E');
System.out.println(sb); // hEllo
//反转字符串 reverse();
StringBuffer sbf = new StringBuffer("java");
sbf.reverse();
System.out.println(sbf); // 输出:avaj
//删除字符串 deleteCharAt(int index); 或 delete(int start,int end) ;
StringBuffer sbf1 = new StringBuffer("She");
sbf1.deleteCharAt(2);
System.out.println(sbf1); // Sh
StringBuffer sbf2 = new StringBuffer("hello jack");
sbf2.delete(2,5);
System.out.println(sbf2); // he jack 删除从2(包括2)到5(不包括5)
五、System
1.System 类有 3 个静态成员变量,分别是 PrintStream out、InputStream in 和 PrintStream err
public final static InputStream in;
//标准输入流;println 方法是属于流类 PrintStream 的方法,而不是 System 中的方法
public final static PrintStream out;
//标准输出流;此流已打开并准备提供输入数据。通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源
public final static PrintStream err;
//标准错误流;其语法与 System.out 类似,不需要提供参数就可输出错误信息。也可以用来输出用户指定的其他信息,包括变量的值
2.常用方法
(1)arraycopy() 方法
该方法的作用是数组复制,即从指定源数组中复制一个数组
//public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length),其中,src 表示源数组,srcPos 表示从源数组中复制的起始位置,dest 表示目标数组,destPos 表示要复制到的目标数组的起始位置,length 表示复制的个数
public class SystemArrayCopy {
public static void main(String[] args) {
char[] srcArray = {'A','B','C','D'};
char[] destArray = {'E','F','G','H'};
System.arraycopy(srcArray,1,destArray,1,2);
System.out.println("源数组:");
for(int i = 0;i < srcArray.length;i++) {
System.out.println(srcArray[i]);
}
System.out.println("目标数组:");
for(int j = 0;j < destArray.length;j++) {
System.out.println(destArray[j]);
}
/*
源数组:
A
B
C
D
目标数组:
E
B
C
H
*/
}
}
(2)currentTimeMillis() 方法
该方法的作用是返回当前的计算机时间
long m = System.currentTimeMillis();
(3)exit() 方法
该方法的作用是终止当前正在运行的 Java 虚拟机
//public static void exit(int status);
(4)gc() 方法
该方法的作用是请求系统进行垃圾回收,完成内存中的垃圾清除
//public static void gc();
(5)getProperty() 方法
该方法的作用是获得系统中属性名为 key 的属性对应的值
//public static String getProperty(String key);
六、Data
1.表示特定的瞬间。精确到毫秒
public Date();
public Data(Long data);
2.常用方法
getTime()方法
Date date = new Date();
long time = date.getTime();
3.DataFromat类
(1)DataFromat类是日期/时间格式化子类的抽象类,可以在Data对象与String对象之间进行来回转换;DataFromat为抽象类,不能直接使用,所以需要常用的子类
public SimpleDataFormat(String pattern)// 用给定的模式和默认语言环境的日期格式符号构造SimpleDataFormat
创建SimpleDataFormat对象:
DataFormat format=new SimpleDataFormat(“yyyy-MM-dd HH:mm:ss”);// 年-月-日 时:分:秒
public String format(Data data)//将Data对象格式化为字符串。
public Data parse(String source)//将字符串解析为Data对象。