JAVASE学习笔记:第十二章 集合

因数组一旦创建长度就不能改变集合(collection),将多个相同性质的元素汇聚成一个整体 所在java.util包集合框架(collection framework)一、List是一个有序的、可重复的子接口,ArrayList是实现list的一个子类在集合当中只能存放引用数据类型,不能存放基本数据类型ArrayList list=new ArrayList();list.add(对象);list.add(位置,对象);list.get(2);//获取指定位置的元素,返回的数据类型是对象list.contains(元素) //是否包含这个元素list.size() //元素的个数list.remove(位置) //移除元素,返回值是相对应位置的元素二、泛型 JDK1.5之后的东西,主要是用来约束集合中元素的数据类型ArrayList<String> list=new ArrayList<String>();增加for循环,JDK1.5之后的东西for(String s:list){ System.out.println(s);}通过迭代器,while(it.hasnext()){ it.next();}

通过对象流写对象的过程:因直接将对象写入流,追加读取会报错,所以必须借助ArrayList集合

1、判断文件中是否存在该对象集合,如果不存在则new()一个,如果存在则追加2、创建list对象存储student对象元素3、将list对象写入到data文件中/***通过对象流把list读取和写入到data文件中*2015-6-16*作者 常宝*/

public class testsaveobj {public static void main(String[] args) {Student s=new Student();s.setAge("20");s.setName("ddd");s.setSex(2);testsaveobj t1=new testsaveobj();boolean b=t1.objwrite(s);System.out.println(b);ArrayList<Student> alist=t1.objread();System.out.println(alist.size());}//将存储student元素的list对象写入到data文件中public boolean objwrite(Student s){File f=new File("d:\\data.txt");ArrayList<Student> list;if(f.length()==0){list=new ArrayList<Student>();list.add(s);}else{ list=this.objread();list.add(s);}ObjectOutputStream objOut=null;try { objOut=new ObjectOutputStream(new FileOutputStream(f)); objOut.writeObject(list); return true;} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {objOut.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return false;}//读取data文件里的list对象的student元素public ArrayList<Student> objread(){File f=new File("d:\\data.txt");ObjectInputStream objin=null;if(f.length()==0){System.out.println("文件无内容");}else{try {objin=new ObjectInputStream(new FileInputStream(f));ArrayList<Student> list=(ArrayList<Student>)objin.readObject();return list;} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {objin.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return new ArrayList<Student>();}}

三、HashSet 是无序的、无重复子类因为没有位置,不能通过get获取指定元素值,只能进行增加,删除等操作判断元素是否有重复值是调用hashcode进行比较是否重复值只能通过迭代器进行遍历

渐渐少了联络,友谊就变的淡了,所以,抽点时间,联络朋友一起聊聊天,

JAVASE学习笔记:第十二章 集合

相关文章:

你感兴趣的文章:

标签云: