Java集合&泛型
collection类(list,set)
Map类(HashMap)
泛型类
1.集合(为什么要使用集合,因为在不同条件下,数组的长度是固定的,而集合能自动适应大小)
集合类用于存储数量不等的对象(相较于数组对象)
Java集合大致分为set,list,queue,和Map
set:无序,不可重复的集合
list:有序,可重复的集合
queue:队列集合
Map:具有映射关系的集合
2.collection类
collection接口是list,set和queue接口的父接口
Iterator iterator()迭代器,用于遍历所有的元素
//只输出一个,去重的set
package com.mashen.date;
import java.util.HashSet;
public class SetTest {
public static void main(String[] args) {
HashSet<String> names=new HashSet<>();
names.add("哈哈哈");
names.add("哈哈哈");
names.add("哈哈哈");
System.out.println(names.toString());
}
}
判断set集合元素相同的标准
通过equals()方法比较相等,并且hashcode()返回也相等
3.Map类☞Hsahmap
将键映射到值的对象
package com.mashen.date;
import java.util.HashMap;
import java.util.Map;
public class SumNumber {
public static Map<String,Integer> parseArray(String[] arr){
Map<String, Integer> data=new HashMap<>();
for(String str : arr){
data.put(str, data.get(str)==null?1:data.get(str)+1);
}
return data;
}
public static void main(String[] args) {
String[] arr={"a","b","a","b","c","a","b","c","b",};
System.out.println(parseArray(arr));
}
}
泛型:类型化参数增加安全性。
package com.mashen.date;
import java.awt.List;
import java.util.ArrayList;
public class Fanxing {
public static void main(String[] args) {
List<String> strList=new ArrayList<String>();
strList.add("码神");
strList.add("android");
strList.add(100);
for(int i=0;i<strList.size();i++){
String string=(String)strList.get(i);
System.out.println(string.length());
}
}
}
异常
throws
使用,eg: throws new EOFException;
t
ry{}catch{}的使用,trycatch主要用于捕获已知异常,可以保证程序正常运行并且显示错误信息;可以使用try捕获多个异常。
finally字句
执行条件:
1.代码中没有抛出异常
2.抛出一个在catch字句中捕获的异常;
3.代码抛出异常,但不是catch捕获的异常
try语句中可以有finally而没有catch
我认为哈,try/catch,try/finally最好独立使用,可以增加代码的清晰行
package com.mashen.date;
public class FianllyT {
public static void main(String[] args) {
int i=0;
String greetings[]={"hello world!","hello world!!","hello world!!!"};
while (i<4){
try{
System.out.println(greetings[i++]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组下标越界异常");
}finally{
System.out.println("-----------------");
}
}
}
}