Java基础
Collection集合
1.单列集合Collection
List集合
(ArrayList、linkedList、Vector(不常用))
1特点: 有序,有索引,可重复
2遍历方法:1.普通for
2.转数组
3.迭代器
4.增强for
set集合(用自定类时 需要在类中重写hashcode和equals方法)
(HashSet、LinkedHashSet(有序)、TreeSet)
1 特点: 无序,无索引,不可重复
2遍历方法:1.转数组
2.迭代器
3.增强for
2. 常用方法
增
public boolean add(E)
删
public void clear()
public boolean remove(E)
改
public Object[] toArray()
public T[] toArray(<T>)
查
public int size()
public boolean isEmpty()
迭代器
1.获取迭代器对象
//使用 集合对象名.iterator()方法 获取迭代器
Iterator<E> it = c.iterator();
2.使用迭代器方法
it.hasNext(); //是否存在下一个元素 迭代器对象名.hasNest
E e = it.next(); //获取下一个元素 迭代器对象名.next
案例
//创建对象
Collection<String> a = new ArrayList<String>();
//添加数据
a.add("Hello");
a.add("world");
a.add("good");
//获取迭代器
Iterator<String> it = c.iterator();
//循环遍历迭代器 快捷键 itit+回车
while (it.hasNext()) {
String next = it.next();
System.out.println(next);
}
3.增强for循环 (快捷键 集合名称.for)
案列展示
//创建对象
Collection<String> c = new ArrayList<String>();/
// /添加数据
c.add("Hello");
c.add("world");
c.add("God");
//增强for
for (String s : c) {
System.out.println(s);
}
泛型
1使用泛型的好处
A.提前检查(运行时可能出现的类型转换异常,提前到编译时是否通过)
B.简洁代码(不需要手动向下转型,快捷键直接提示出来类型)
2泛型应用场景
A.泛型类
a.定义格式:
//定义未知不具体类型
修饰符 class 类名称<泛型>{ }
b.使用格式:(创建对象)
//使用已知具体类型
类名称<具体类型> 对象名称 = new 类名称<具体类型>();
B.泛型方法
a.定义格式:
//定义未知不具体类型
修饰符 <泛型> 返回值 方法名称 (参数){ 方法体; return返回值;}
b.使用格式:(调用方法)
//使用已知具体类型
具体返回值类型 返回值 = 方法名称(具体参数);
C.泛型接口
a.定义格式:
修饰符 interface 接口名称<泛型>{ }
b.使用格式:(实现类或者创建实现类对象时候)
//使用已知具体类型
第一种:修饰符 class 类名称 implements 接口名称<具体类型>{ }
//使用已知具体类型
第二种:类名称<具体类型> 对象名称 = new 类名称<具体类型>();
D.泛型通配符
a.含义: 不知道使用什么数据类型的时候,泛型可以使用 ?
b.格式: Collection<?> 可以传递各种泛型类型的对象
例如: 这些都可以传递 Collection<Object> Collection<String> Collection<Integer>
c.高级使用: (Number是Integer的父类)
Collection<? extends Number> 只能接收 Number类型以及子类类型. (专业术语"泛型的上限")
Collection<? super Number> 只能接收 Number类型以及父类类型. (专业术语"泛型的下限")
案例
//编写一个泛型方法,接收一个任意引用类型的数组,并反转数组中的所有元素
public class test4 {
public static void main(String[] args) {
Integer[] a={1,2,5,6,7};
String[] b={"张三","李四","赵六","25","36"};
System.out.println(Arrays.toString(method(b)));
System.out.println(Arrays.toString(method(a)));
}
private static <M> M[] method(M[] m) {
for (int i = 0; i < m.length/2; i++) {
M m1 = m[i];
m[i]=m[m.length-1-i];
m[m.length-1-i]=m1;
}
return m;
}
}