Java 容器与集合

 

目录

一、容器概念

二、Collection 接口

1. Collection接口有两个子接口Set和List

2. Collection中常用方法:

3. 代码示范:

4. Collection的遍历

5.  泛型 < >

三、Iterator 接口

1. Iterator的特点

2. Iterator接口常用方法

3. 使用迭代器时的步骤

四、List接口

1. 特征

2. 常用方法

3. List的遍历

4. 解决并发增加问题

五、ArrayList类

1. 特点

2. ArrayList常用方法

3. ArrayList的遍历

4. ArrayList储存对象

六、LinkedList类

1. 特点

2. LinkedList遍历和常用方法

七、Set接口 

1. 特点

2. Set常用方法

3. Set的遍历

八、HashSet类

1. 特点

2. 遍历

3. 常用方法

4. HashSet去重

5. 代码示范

九、Map接口

1. 特征

2. Map常用方法

3. Map的遍历

4. 引用类型数据去重

5. Properties类

十、Collections工具类

1. 特征

2. Collections常用方法

3. 代码示范

十一、File类

1. 概念

2. 要点

3. 常用方法

         (1)创建功能

(2)重命名和删除功能

(3)判断功能

(4)获取功能


一、容器概念

    数组是一种简单的线性序列,可以快速的访问数组元素,效率高,但是从数组 长度一旦确定,不可改变,因此,数组远远不能满足我们的需求。 我们需要一种灵活的,容量可以随时扩充的容器来装载我们的对象,这就需要用到容器类,或者叫集合框架。

体系图如下:

  1. Collection 接口是一组允许重复的对象。
  2. Set 接口继承 Collection,无序不允许重复,使用自己内部的一个排列机制。
  3. List 接口继承 Collection,有序允许重复,以元素安插的次序来放置元素,不会重新排列。
  4. Map 接口是一组成对的键值对象,即所持有的是 key-value pairs。Map 中不能有重复的 key。拥有自己的内部排列机制。
  5. 容器中的元素类型都为引用类型, 不能放置原生数据类型(使用装箱即可),使用泛型保留类型。

二、Collection 接口

1. Collection接口有两个子接口Set和List

  • Set 中的数据没有顺序,不可重复;
  • List 中的数据有顺序,可重复。

2. Collection中常用方法:

方法摘要
 booleanadd(E e)
          确保此 collection 包含指定的元素(可选操作)。
 booleanaddAll(Collection<? extends E> c)
          将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。
 voidclear()
          移除此 collection 中的所有元素(可选操作)。
 booleancontains(Object o)
          如果此 collection 包含指定的元素,则返回 true。
 booleancontainsAll(Collection<?> c)
          如果此 collection 包含指定 collection 中的所有元素,则返回 true。
 booleanequals(Object o)
          比较此 collection 与指定对象是否相等。
 inthashCode()
          返回此 collection 的哈希码值。
 booleanisEmpty()
          如果此 collection 不包含元素,则返回 true。
 Iterator<E>iterator()
          返回在此 collection 的元素上进行迭代的迭代器。
 booleanremove(Object o)
          从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。
 booleanremoveAll(Collection<?> c)
          移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。
 booleanretainAll(Collection<?> c)
          仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。
 intsize()
          返回此 collection 中的元素数。
 Object[]toArray()
          返回包含此 collection 中所有元素的数组。
<T> T[]
toArray(T[] a)
          返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。

3. 代码示范:

public static void main(String[] args) {
		//1.创建容器
		Collection c=new ArrayList();
		/*
		 * 2.添加元素
		 * boolean add(E e) 
			          确保此 collection 包含指定的元素(可选操作)。 
		   boolean addAll(Collection<? extends E> c) 
			          将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。 
		 */
		c.add("清华大学");
		c.add("北京大学");
		Collection c2=new ArrayList();
		c2.add("哈工大");
		c2.add("佳木斯大学");
		c2.add(1); //Integer 自动装箱
		System.out.println(c.size());
		c.addAll(c2);
		
		/*
		 * 3.获取
		 *  int size() 
          		返回此 collection 中的元素数。 
          	boolean isEmpty() 
          		如果此 collection 不包含元素,则返回 true。 
		 */
		System.out.println(c.size());
		System.out.println("判断是否为空:"+c.isEmpty());
		System.out.println(c);
		
		/*
		 * 4.删除
		 *  void clear() 
          		移除此 collection 中的所有元素(可选操作)。 
          	boolean remove(Object o) 
          		从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。 
          	boolean removeAll(Collection<?> c) 
          		移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。 
          	boolean retainAll(Collection<?> c) 
          		仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。 
		 */
		System.out.println(c.size());
		System.out.println("remove:"+c.remove("清华大学"));
		System.out.println(c.size());
		//System.out.println("removeAll:"+c.removeAll(c2));
		System.out.println("removeAll:"+c.retainAll(c2));
		System.out.println(c.size());
        //c.clear();
		System.out.println(c.size());
		System.out.println("判断是否为空:"+c.isEmpty());
		
		/*
		 *  Object[] toArray() 
          		返回包含此 collection 中所有元素的数组。 
		 */
		 Object[] obj=c.toArray();
		 System.out.println(Arrays.toString(obj));
		
		/*
		 * 5.是否包含
		 *  boolean contains(Object o) 
          		如果此 collection 包含指定的元素,则返回 true。 
		 */
		System.out.println(c.contains("佳木斯大学"));

4. Collection的遍历

        Collection因为没有索引去定位,因此普通for循环无法使用,可以使用增强for循环和迭代器来遍历它。

  • 增强for循环
  • 迭代器
public static void main(String[] args) {
		Collection c=new ArrayList();
		c.add("拇指");
		c.add("食指");
		c.add("中指");
		c.add("无名指");
		c.add("小手指");
		
		//foreach循环
		for(Object s:c){
			System.out.println(s);
		}
		
		System.out.println("----------------------------------");
		//使用迭代器
		//1.获取一个迭代器对象 凡是实现了Collection接口的类都有iterator()方法
		Iterator it=c.iterator();
		//2.判断是否还有下一个元素
		while(it.hasNext()){
			//3.如果有下一个元素就使用next()方法获取
			//String s=(String) it.next();
			Object s = it.next();
			System.out.println(s);
		}
	}

5.  泛型 < >

  • 为什么需要泛型?
  1. 装入集合的类型都被当作 Object 对待,从而失去自己的实际类型,使用泛型,保留了容器中元素的类型。
  2. 从集合中取出时往往需要转型,效率低,容易产生错误。
  • 泛型的好处:增强程序的可读性和稳定性。
  • 注意:没有必要引入泛型的复杂性。

三、Iterator 接口

1. Iterator的特点

    所有实现了 Collection  接口的容器类个 都有一个 iterator  方法用以返回一个实现了 Iterator 接口的对象。Iterator 对象称作迭代器,用以方便的实现对容器内元素的遍历操作。

2. Iterator接口常用方法

boolean hasNext(); //判断是否有元素没有被遍历
Object next(); //返回游标当前位置的元素并将游标移动到下一个位置
void remove(); //删除游标左面的元素

3. 使用迭代器时的步骤

//使用迭代器
//1.获取一个迭代器对象 
Iterator it=c.iterator();
//2.判断是否存在下一个元素
while(it.hasNext()){
	//3.如果有下一个元素就使用next()方法获取
	//String s=(String) it.next();
	Object s = it.next();
	System.out.println(s);
}

四、List接口

1. 特征

有序的,可重复的。

2. 常用方法

方法摘要
 booleanadd(E e)
          向列表的尾部添加指定的元素(可选操作)。
 voidadd(int index, E element)
          在列表的指定位置插入指定元素(可选操作)。
 booleanaddAll(Collection<? extends E> c)
          添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序(可选操作)。
 booleanaddAll(int index, Collection<? extends E> c)
          将指定 collection 中的所有元素都插入到列表中的指定位置(可选操作)。
 voidclear()
          从列表中移除所有元素(可选操作)。
 booleancontains(Object o)
          如果列表包含指定的元素,则返回 true。
 booleancontainsAll(Collection<?> c)
          如果列表包含指定 collection 的所有元素,则返回 true。
 booleanequals(Object o)
          比较指定的对象与列表是否相等。
 Eget(int index)
          返回列表中指定位置的元素。
 inthashCode()
          返回列表的哈希码值。
 intindexOf(Object o)
          返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
 booleanisEmpty()
          如果列表不包含元素,则返回 true。
 Iterator<E>iterator()
          返回按适当顺序在列表的元素上进行迭代的迭代器。
 intlastIndexOf(Object o)
          返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1。
 ListIterator<E>listIterator()
          返回此列表元素的列表迭代器(按适当顺序)。
 ListIterator<E>listIterator(int index)
          返回列表中元素的列表迭代器(按适当顺序),从列表的指定位置开始。
 Eremove(int index)
          移除列表中指定位置的元素(可选操作)。
 booleanremove(Object o)
          从此列表中移除第一次出现的指定元素(如果存在)(可选操作)。
 booleanremoveAll(Collection<?> c)
          从列表中移除指定 collection 中包含的其所有元素(可选操作)。
 booleanretainAll(Collection<?> c)
          仅在列表中保留指定 collection 中所包含的元素(可选操作)。
 Eset(int index, E element)
          用指定元素替换列表中指定位置的元素(可选操作)。
 intsize()
          返回列表中的元素数。
 List<E>subList(int fromIndex, int toIndex)
          返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。
 Object[]toArray()
          返回按适当顺序包含列表中的所有元素的数组(从第一个元素到最后一个元素)。
<T> T[]
toArray(T[] a)
          返回按适当顺序(从第一个元素到最后一个元素)包含列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。

3. List的遍历

       List因为是有序的,所以可以使用索引,因此我们有三种方式可以遍历它。

  • 普通for循环
  • 增强for循环
  • 迭代器
public static void main(String[] args) {
     List<String> ls=new ArrayList();
		
		//增加
		ls.add("钢铁侠");
		ls.add("雷神");
		ls.add("灭霸");
		ls.add("美国队长");
		//1--------------for--------------
		for(int i=0;i<ls.size();i++){
			System.out.println(ls.get(i));
		}
		
		//2--------------foreach--------------
		for(String s:ls){
			System.out.println(s);
		}
		
		//3--------------迭代器--------------
		//1)获取迭代器对象
		Iterator it=ls.iterator();
		//2)判断是否存在下一个元素
		while(it.hasNext()){
			//3)获取
			System.out.println(it.next());
		}
	}

4. 解决并发增加问题

    List在使用增强for和迭代器来遍历元素时,由于多个引用同时调用会引发多并发异常问题。

    ConcurrentModificationException:方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。

    解决并发增加问题:使用 ListIterator 

//3--------------迭代器--------------  底层是由foreach实现的
		//ConcurrentModificationException 
		//1)获取迭代器对象
	/*	Iterator it=ls.iterator();
		//2)判断是否存在下一个元素
		while(it.hasNext()){
			//3)获取
			if(it.next().equals("灭霸")){
				ls.add("惊奇队长");
			}
		}
		System.out.println(ls);*/
		
		//4.-----------解决并发增加问题:使用 ListIterator 
		//1.获取迭代器
		 ListIterator li=ls.listIterator();
		 //判断
		 while(li.hasNext()){
			 if(li.next().equals("灭霸")){
				 li.add("惊奇队长");
			 }
		 }
		 System.out.println(ls);
	}

五、ArrayList类

1. 特点

    ArrayList 是 List 的子类,它和 HashSet 相反,允许存放重复元素,因此有序。

  1. 底层由可变数组结构实现。
  2. 优点:查询,以及随机获取效率高。
  3. 缺点:增加,删除效率低。
  4. 动态扩容:使用copyof进行扩容,新数组的大小是原数组的1.5倍。

2. ArrayList常用方法

由于ArrayList是List的实现类,因此继承了List的所有方法,常用方法也基本相同。

3. ArrayList的遍历

同List接口的遍历方式相同

  • 普通for循环
  • 增强for循环
  • 迭代器

4. ArrayList储存对象

    注意: ArrayList在储存对象时,使用indexOf方法时调用的equals方法比较的是地址,如果要比较内容需要重写equals方法,生成快捷键Alt+S.

public class ArrayListTest09{
	public static void main(String[] args) {
		List<Person> ls=new ArrayList();
		ls.add(new Person("欢欢",18));
		ls.add(new Person("书书",19));
		System.out.println(ls.indexOf(new Person("书书",19))); //-1 因为Person中没有重写equals方法
		
		List<String> ls2=new ArrayList();
		ls2.add(new String("么么"));
		System.out.println(ls2.indexOf(new String("么么"))); // 0  因为String类型中重写了squals方法
	}
}

class Person{
	private String name;
	private int age;
	
	public Person() {
		super();
	}
	
	public Person(String name, int age) {
		super();
		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;
	}

	//重写equals方法,比较内容
	@Override
	/*public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}*/
	
}

六、LinkedList类

1. 特点

    LinkedList 可以重复,是一种可以在任何位置进行高效地插入和删除操作的有序序列。

  1. 实现结构:是由链表结构实现的。
  2. 优点:插入,删除效率高。
  3. 缺点:查询,随机获取效率低。
  4. 新增了一些操作类表头和类表尾的方法。

2. LinkedList遍历和常用方法

    LinkedList同ArrayList一样都为List的一个实现类,因此它的遍历方式和常用方法同List基本相同。

public static void main(String[] args) {
	LinkedList ls=new LinkedList();
	ls.add("哈哈");
	ls.add("呵呵");
	ls.add("嘿嘿");
		
	System.out.println("getFirst:"+ls.getFirst());
	System.out.println("getFirst:"+ls.peek());
	System.out.println("getFirst:"+ls.peekFirst());
		
}

七、Set接口 

1. 特点

 Set 接口中的元素无序不可重复,不包含重复元素,最多包含一个 null,元素没有顺序 。

2. Set常用方法

Set继承了Collection接口的所有方法,没有新增方法。

3. Set的遍历

Set同父级接口Collection相同,没有索引,只能通过增强for和迭代器来遍历元素。

八、HashSet类

1. 特点

    HashSet 是 Set 接口的一个子类,主要的特点是:里面不能存放重复元素,而且采用散列的存储方法,所以没有顺序。这里所说的没有顺序是指:元素插入的顺序与输出的顺序不一致。

  1. 由哈希表的数据结构存储的  哈希表=数组+链表
  2. 优点:查询  增加  删除  效率高
  3. 缺点:无序的

2. 遍历

    由于是无序,无法操作索引,因此与Set相同,只能通过增强for和迭代器遍历。

3. 常用方法

方法摘要
 booleanadd(E e)
          如果此 set 中尚未包含指定元素,则添加指定元素。
 voidclear()
          从此 set 中移除所有元素。
 Objectclone()
          返回此 HashSet 实例的浅表副本:并没有复制这些元素本身。
 booleancontains(Object o)
          如果此 set 包含指定元素,则返回 true。
 booleanisEmpty()
          如果此 set 不包含任何元素,则返回 true。
 Iterator<E>iterator()
          返回对此 set 中元素进行迭代的迭代器。
 booleanremove(Object o)
          如果指定元素存在于此 set 中,则将其移除。
 intsize()
          返回此 set 中的元素的数量(set 的容量)。

4. HashSet去重

  1. 重写hashcode 与 equals。
  2. 先调用hashcode,如果计算出来的位置不相同,默认就是两个对象。
  3. 如果hashcode值相同,再去调用equals,去比较内容。

注意:Set下还有个TreeSet类

  •     它是有序的(排序--升序)  不可重复的
  •     使用二叉树结构存储

5. 代码示范

public class HashSetDemo12 {
	public static void main(String[] args) {
		HashSet<User> set=new HashSet<>();
		set.add(new User("李健",40));
		set.add(new User("谢霆锋",41));
		set.add(new User("李健",40));
		System.out.println(set.size());
		for(User u:set){
			System.out.println(u.hashCode());
		}
		
		TreeSet tr=new TreeSet();
		tr.add("c");
		tr.add("b");
		tr.add("哈哈");
		tr.add("a");
		tr.add("呵呵");
		tr.add("e");
		System.out.println(tr);
		System.out.println(tr.ceiling("b"));  //c
		System.out.println(tr.floor("b"));  //a
		System.out.println(tr.higher("b"));  //c
		System.out.println(tr.pollFirst());  //c
	}
}

class User{
	private String name;
	private int 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 User(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

九、Map接口

1. 特征

Map是一种用来存储键值对形式的数据的接口:K(key)  -  V(value)。

  1.  key 键:唯一的  无序的  ---Set集合。
  2.  value 值: 无序的  不是唯一的。
  3.  一个key只能对应一个value(value作为list)。
  4.  Map中存放值,如果key相同,后面的会覆盖前面的值。

Map 接口的实现类有 HashMap 和 TreeMap 等。

  • HashMap:线程不安全,效率高,允许 key 或 value 为 null。
  • HashTable:线程安全,效率低,不允许 key 或 value 为 null。
  • Properties:Hashtable 的子类,key 和 value 都是 string。

2. Map常用方法

方法摘要
 voidclear()
          从此映射中移除所有映射关系(可选操作)。
 booleancontainsKey(Object key)
          如果此映射包含指定键的映射关系,则返回 true。
 booleancontainsValue(Object value)
          如果此映射将一个或多个键映射到指定值,则返回 true。
 Set<Map.Entry<K,V>>entrySet()
          返回此映射中包含的映射关系的 Set 视图。
 booleanequals(Object o)
          比较指定的对象与此映射是否相等。
 Vget(Object key)
          返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null
 inthashCode()
          返回此映射的哈希码值。
 booleanisEmpty()
          如果此映射未包含键-值映射关系,则返回 true。
 Set<K>keySet()
          返回此映射中包含的键的 Set 视图。
 Vput(K key, V value)
          将指定的值与此映射中的指定键关联(可选操作)。
 voidputAll(Map<? extends K,? extends V> m)
          从指定映射中将所有映射关系复制到此映射中(可选操作)。
 Vremove(Object key)
          如果存在一个键的映射关系,则将其从此映射中移除(可选操作)。
 intsize()
          返回此映射中的键-值映射关系数。
 Collection<V>values()
          返回此映射中包含的值的 Collection 视图。

3. Map的遍历

Map因为是无序的,所以可以用到增强for循环和迭代器去遍历,又因为有键 - 值的存在,所以可以用键或者值去进行遍历。

Map中还提供了另外一种遍历方法,使用Map.entrySet(); 这个方法返回的是一个Set<Map.Entry<K,V>>,Map.Entry 是Map中的一个内部接口,他的用途是表示一个映射项(里面有Key和Value),而Set<Map.Entry<K,V>>表示一个映射项的Set。Map.Entry里有相应的getKey和getValue方法,即JavaBean,让我们能够从一个项中取出Key和Value。

public static void main(String[] args) {
  
  Map<String, String> map = new HashMap<String, String>();
  map.put("1", "value1");
  map.put("2", "value2");
  map.put("3", "value3");
  
  //第一种:普遍使用,二次取值
  System.out.println("通过Map.keySet遍历key和value:");
  for (String key : map.keySet()) {
   System.out.println("key= "+ key + " and value= " + map.get(key));
  }
  
  //第二种
  System.out.println("通过Map.entrySet使用iterator遍历key和value:");
  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
  while (it.hasNext()) {
   Map.Entry<String, String> entry = it.next();
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }
  
  //第三种:推荐,尤其是容量大时
  System.out.println("通过Map.entrySet遍历key和value");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }
 
  //第四种
  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
  for (String v : map.values()) {
   System.out.println("value= " + v);
  }
 }

4. 引用类型数据去重

引用数据类型去重,我们把内容一样认为相同,解决办法:重写hashCode和equals方法。

public class MapTest05 {
	public static void main(String[] args) {
		Map<Hero,Integer> maps=new HashMap<>();
		maps.put(new Hero("亚瑟",450),1);
		maps.put(new Hero("李白",18888),2);
		maps.put(new Hero("李白",18888),3);
		
		System.out.println(maps.size());
	}
}

class Hero{
	private String name;
	private int money;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getMoney() {
		return money;
	}
	public void setMoney(int money) {
		this.money = money;
	}
	public Hero(String name, int money) {
		super();
		this.name = name;
		this.money = money;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + money;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Hero other = (Hero) obj;
		if (money != other.money)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

5. Properties类

Properties为Hashtable的子类,要求键与值只能为字符串,不能为null,常用于配置文件(与外界交互的信息) 即内存与存储介质(文件、数据库、网络、服务器内存等)交互。

public class PropertiesDemo07 {
	
		/*pro.setProperty("name", "裴秀智");
		pro.setProperty("age", "25");
		System.out.println(pro.getProperty("name"));
*/

	public static void main(String[] args) throws IOException {
		Properties pro = new Properties();
		
		pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
		System.out.println(pro.getProperty("name"));
	}
}

十、Collections工具类

1. 特征

类 java.util.Collections 提供了对容器操作的工具方法,与 Arrays 使用差不多。

2. Collections常用方法

  • void sort(List) //对 List 容器内的元素排序,按照升序进行排序。
  • void shuffle(List) //对 List 容器内的元素进行随机排列
  • void reverse(List) //对 List 容器内的元素进行逆续排列
  • void fill(List, Object) //用一个特定的对象重写整个 List 容器
  • int binarySearch(List, Object)//采用折半查找的方法查找特定对象

3. 代码示范

public class CollectionsDemo06 {
	public static void main(String[] args) {
		List<String> ls=new ArrayList();
		
		ls.add("杨千嬅");
		ls.add("杨超越");
		ls.add("裴秀智");
		ls.add("全智贤");
		
		System.out.println(ls);
		Collections.reverse(ls);
		System.out.println(ls);
		Collections.shuffle(ls);
		System.out.println(ls);
		
//		Collections.fill(ls, "范冰冰");
		System.out.println(ls);
		
		Collections.sort(ls);
		System.out.println(ls);
		System.out.println(Collections.binarySearch(ls, "裴秀智"));
		
		GirlFriend g1=new GirlFriend("nice",0);
		GirlFriend g2=new GirlFriend("soso",1);
		GirlFriend g3=new GirlFriend("good",0);
		List<GirlFriend> list=new ArrayList();
		list.add(g1);
		list.add(g2);
		list.add(g3);
		System.out.println(list);
		
		Collections.sort(list);
		System.out.println(list);
		
	}
}

class GirlFriend implements Comparable<GirlFriend>{
	private String body;
	private int sex;  //1  男孩  0女孩
	public GirlFriend(String body, int sex) {
		super();
		this.body = body;
		this.sex = sex;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "GirlFriend [body=" + body + ", sex=" + sex + "]";
	}
	@Override
	public int compareTo(GirlFriend o) {
		return this.sex-o.sex;
	}
	
}

十一、File类

1. 概念

在 Java 中, File类是一种用来表示文件和目录路径名的抽象形式。

2. 要点

  1. File 仅代表一个联系,可能文件存在,也可能不存在;
  2. 这里的文件可以是文件,也可以是文件夹。
  3. File 类的实例是不可变的;也就是说,一旦创建,File 对象表示的抽象路径名将永不改变。

3. 常用方法

 (1)创建功能

public boolean createNewFile()

  1. 当且仅当不存在具有此路径名指定名称的文件时,不可分地创建一个新的空文件。
  2. 检查文件是否存在,若不存在则创建该文件,为单个操作,对于其他所有可能影响该文件的文件系统活动来说,该操作是不可分的。
  3. 如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false。 

public boolean mkdirs()

  1. 创建此路径名指定的目录,包括所有必需但不存在的父目录。
  2. 注意,此操作失败时也可能已经成功地创建了一部分必需的父目录。 
  3. 返回:当且仅当已创建目录以及所有必需的父目录时,返回 true;否则返回 false 。

public boolean mkdir()

  1. 创建此抽象路径名指定的目录。 
  2. 返回:当且仅当已创建目录时,返回 true;否则返回 false。
  3. 注意事项:如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。  
public class Create {
 
	/**
	 * @author Xss
	 */
	public static void main(String[] args) throws IOException {
		File file = new File("xy.txt");//相对路径,refresh当前项目或f5
		System.out.println(file.createNewFile());//如果没有就创建,返回true
		
		File file2 = new File("xy");
		System.out.println(file2.createNewFile());
		
		File dir1 = new File("aaa");
		System.out.println(dir1.mkdir());
		
		File dir2 = new File("bbb.txt");//这样写是可以的,文件夹也是可以有后缀的
		System.out.println(dir2.mkdir());
		
		File dir3 = new File("ccc\\ddd");
		System.out.println(dir3.mkdirs()); //创建多级目录
		File dir4 = new File("bbb.txt\\ddd");
		System.out.println(dir4.mkdirs()); //创建多级目录
	}
}

(2)重命名和删除功能

public boolean renameTo(File dest)

  1. 重新命名此路径名表示的文件。 
  2. 此方法行为的许多方面都是与平台有关的: 重命名操作无法将一个文件从一个文件系统移动到另一个文件系统,该操作不是不可分的, 如果已经存在具有目标抽象路径名的文件,那么该操作可能无法获得成功。
  3. 应该始终检查返回值,以确保重命名操作成功。 
  4. 参数: dest - 指定文件的新路径名。 
  5. 返回: 当且仅当重命名成功时,返回 true;否则返回 false 。

public boolean delete()

  1. 删除此抽象路径名表示的文件或目录。
  2. 如果此路径名表示一个目录,则该目录必须为空才能删除。 
  3. 返回: 当且仅当成功删除文件或目录时,返回 true;否则返回 false 。

重命名注意事项

* 如果路径名相同,就是改名。

* 如果路径名不同,就是改名并剪切。

删除注意事项:

* Java中的删除不走回收站。

* 要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹。

public class Name {

         /**
	 * @author Xss
	 */
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file1 = new File("xy.txt");
		File file2 = new File("D:\\xxx.txt");
		//改名并剪贴
		System.out.println(file1.renameTo(file2));
		
		System.out.println(file2.delete());
	}
}

(3)判断功能

public boolean isDirectory():判断是否是目录

public boolean isFile():判断是否是文件

public boolean exists():判断是否存在

public boolean canRead():判断是否可读

public boolean canWrite():判断是否可写

public boolean isHidden():判断是否隐藏

public class judge {

        /**
         * 
         * @author Xss
         *
         */
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File dir0 = new File("ccc");
		System.out.println(dir0.isDirectory());	//判断是否是文件夹
		
		File dir1 = new File("zzz");
		System.out.println(dir1.isDirectory());
		
		System.out.println(dir0.isFile());//判断是否是文件
		System.out.println(dir1.isFile());
		
		File file = new File("zzz");
		file.setReadable(false);
		System.out.println(file.canRead()); //windows系统认为所有的文件都是可读的
		file.setWritable(true);
		System.out.println(file.canWrite()); //windows系统可以设置为不可写
		
		File file2 = new File("aaa.txt");
		System.out.println(file2.isHidden());//判断是否是隐藏文件
		System.out.println(file.isHidden());
	}
 
}

(4)获取功能

public String getAbsolutePath()

  1. 返回此路径名的绝对路径名字符串。 
  2. 如果此路径名已经是绝对路径名,则返回该路径名字符串,这与 getPath() 方法一样。
  3. 如果此路径名是空路径名,则返回当前用户目录的路径名字符串,该目录由系统属性 user.dir 指定。否则,使用与系统有关的方式解析此路径名。
  4. 在 UNIX 系统上,根据当前用户目录解析相对路径名,可使该路径名成为绝对路径名。
  5. 在 Microsoft Windows 系统上,根据路径名指定的当前驱动器目录(如果有)解析相对路径名,可使该路径名成为绝对路径名;否则,可以根据当前用户目录解析它。 
  6. 返回:绝对路径名字符串,它与此路径名表示相同的文件或目录。

public String getPath()

  1. 将此路径名转换为一个路径名字符串。所得字符串使用默认名称分隔符分隔名称序列中的名称。 
  2. 返回:此抽象路径名的字符串形式。

public String getName()

  1. 返回由此路径名表示的文件或目录的名称。
  2. 该名称是路径名名称序列中的最后一个名称。
  3. 如果路径名名称序列为空,则返回空字符串。 
  4. 返回:此路径名表示的文件或目录的名称;如果路径名的名称序列为空,则返回空字符串。


public long length()

  1. 返回由此抽象路径名表示的文件的长度。
  2. 如果此路径名表示一个目录,则返回值是不确定的。 
  3. 返回:此路径名表示的文件的长度,以字节为单位;如果文件不存在,则返回 0L。
  4. 对于表示特定于系统的实体(比如设备或管道)的路径名,某些操作系统可能返回 0L。 

public long lastModified()

  1. 返回此抽象路径名表示的文件最后一次被修改的时间。 
  2. 返回:表示文件最后一次被修改的时间的 long 值,用与时间点(1970 年 1 月 1 日,00:00:00 GMT)之间的毫秒数表示;
  3. 如果该文件不存在,或者发生 I/O 错误,则返回 0L。 

public String[ ] list()

  • 返回一个字符串数组,这些字符串指定此路径名表示的目录中的文件和目录。 

public String[] list(FilenameFilter filter)

  • 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录。
public class d {
 
	/**
	 * @author Xss
	 * 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File file1 = new File("ccc.txt");
		System.out.println(file1.createNewFile());
		File file2 = new File("f:\\ccc.txt");
		System.out.println(file2.createNewFile());
		System.out.println(file1.getAbsolutePath());//获取绝对路径
		//D:\Android\adt-bundle-windows-x86\workplace\dsdsdad\ccc.txt
		System.out.println(file2.getAbsolutePath());
		//D:\ccc.txt
		
		System.out.println(file1.getPath());//获取构造方法中传入路径,ccc.txt
		System.out.println(file2.getPath());//D:\ccc.txt
		
		System.out.println(file1.getName());//获取文件或者文件的名字,ccc.txt
		System.out.println(file2.getName());//ccc.txt
	
		System.out.println(file1.length());//0,e-1
		
		Date d = new Date(file1.lastModified());//文件的最后修改时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		System.out.println(sdf.format(d));//ok
		
		
		File dir = new File("F:\\tools\\java\\util");
		String[] arr = dir.list();		//仅为了获取文件名
		for (String string : arr) {
			System.out.println(string);
		}
		
		File[] subFiles = dir.listFiles();
		for (File file : subFiles) {	//获取文件对象
			System.out.println(file);
		}
	}
 
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值