map接口

目录

1. Comparable类

1.1 重写compareTo

1.2 内部比较器

2. Map接口

2.1 HashMap实现类

2.1.1 遍历

2.1.2 练习:统计单词出现的次数

2.2 TreeMap实现类

2.3 HashTable实现类

2.3.1 Properties

3. Collections工具类

3.1 定义

3.2 方法

4. IO

4.1 File


  • 1. Comparable类

  • 1.1 重写compareTo

 * Person类,Person对象的数据存储到一个数组中,对其排序
 * 引用数据类型 进行排序 sort
 * 实现了Comparable相当于具有了比较的能力,需要重写compareTo,定义比较规则

  • 1.2 内部比较器

 * 内部比较器
 *         缺点:如果更改比较需求,要多次修改方法的实现体,不符合开闭原则

package day14;

import java.util.Arrays;
import java.util.Comparator;

public class ComparableTest01 {
	public static void main(String[] args) {
		Person p1 = new Person("张三", 18);
		Person p2 = new Person("李四", 25);
		Person p3 = new Person("王二", 17);
		Person p[]=new Person[]{p1,p2,p3};
		Arrays.sort(p);
		/*Arrays.sort(p, new Comparator<T>() {
			@Override
			public int compare(Person1 o1, Person1 o2) {
				// return o1.getName().hashCode()-o2.getName().hashCode();
				return o1.getName().compareTo(o2.getName());
			}
		});*/
		System.out.println(Arrays.toString(p));
	}
}
class Person implements Comparable{
	private String name;
	private int age;
	
	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;
	}


	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}


	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		return 0;
	}
}
  • 2. Map接口

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

                HashMap: 线程不安全,效率高. 允许key或value为null

                HashTable:线程安全,效率低. 不允许key 或value 为null

                Properties: Hashtable 的子类,key 和value 都是string

 *  存储键值对形式的数据  K() - V()
 * key键:唯一的,无序的  ---Set集合
 * value 值:不唯一,无序
 * 一个key只能对应一个value(value作为list)
 * Map中存放值,如果key相同,后面的会覆盖前面的值

  • 2.1 HashMap实现类

package day14;

import java.util.HashMap;
import java.util.Map;

public class MapTest03 {
	public static void main(String[] args) {
		//创建一个容器
		Map<Object,String> maps = new HashMap();
		Map<Character,String> maps2 = new HashMap();
		
		/*
		 * 存:put()   putAll()
		 * 
		 * 删:remove()
		 * 
		 * 查:get()
		 * 	 是否包含某个key: containsKey()
		 *   是否包含某个value:containsValue()
		 */
		maps.put(1,"海贼王man");
		maps.put(2,"火影忍者");
		maps.put(3,"四驱兄弟");
		maps.put(3,"龙珠");
		maps.put(null,"null");
		
		maps2.put('a',"海贼王man");
		maps2.put('b',"火影忍者");
		
		maps.putAll(maps2); //两个map容器的泛型必须匹配  ,或者包含
		
		maps.remove(3);
		System.out.println(maps.size());
		System.out.println(maps.get(2));
		System.out.println(maps.containsKey(2));
		System.out.println(maps.containsValue("龙珠"));
		
	}
}
  • 2.1.1 遍历

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

package day14;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapTest04 {
	public static void main(String[] args) {
		//1.创建一个Map容器
		Map<Integer,String> maps =new HashMap<>();
		Map<Integer,String> maps2 =new HashMap<>();
		
		//2.存
		maps.put(1,"海贼王man");
		maps.put(2,"火影忍者");
		maps.put(3,"四驱兄弟");
		maps.put(3,"龙珠");
		
		maps2.put(55,"海贼王man");
		maps2.put(56,"火影忍者");
		
		maps.putAll(maps2); //两个map容器的泛型必须匹配
		System.out.println(maps);
		System.out.println(maps.get(1));
		System.out.println(maps.keySet());
		System.out.println("--------------------");
		
		//遍历----------操作key-----keySet()
		//foreach
		Set<Integer> keyset=maps.keySet();
		for(Integer i:keyset){
			System.out.println(i+"---"+maps.get(i));
		}
		System.out.println("--------------------");
		//for
		for (Iterator<Integer> it =maps.keySet().iterator();it.hasNext();) {
			Integer i=it.next();
			System.out.println(i+"---"+maps.get(i));
		}
		System.out.println("--------------------");
		
		//遍历----------操作values-----
		Collection<String> col = maps.values();
		Iterator it = col.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		System.out.println("----------------------");
		//Set<Map.Entry<K,V>>  entrySet() ---------
		//Map. 可以不写
		Set<Map.Entry<Integer,String>> s = maps.entrySet();
		for(Map.Entry<Integer,String> en:s){
			System.out.println(en.getKey()+"---"+en.getValue());
		}
	}
}
  • 2.1.2 练习:统计单词出现的次数

package day14.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//统计单词出现的次数
//*		this is a cat and that is a mouse where is the food and so on and so on
public class Test1 {
	public static void main(String[] args) {
		String strs = "this is a cat and that is a mouse where is the food and so on and so on";
		// 拆分
		String[] s = strs.split(" ");
		System.out.println(Arrays.toString(s));
		Map<String, Integer> map = new HashMap<>();
		for (int i = 0; i < s.length; i++) {
			// 判断是否存在
			if (!map.containsKey(s[i])) {
				map.put(s[i], 1);// 如果不存在,写入
			} else {
				Integer it = map.get(s[i]);// 如果存在,先查询键对应的值
				map.put(s[i], it + 1);// 覆盖,并修改值
			}
		}

		// 遍历---------keySet--------------
		Iterator<String> it2 = map.keySet().iterator();
		while (it2.hasNext()) {
			String str = it2.next();
			System.out.println("单词:" + str + " --- " + map.get(str) + "次");
		}
		// -------------value----------------
		 Set<Map.Entry<String,Integer>> str=map.entrySet();
		 for(Map.Entry<String,Integer> en:str){
		 System.out.println(en.getKey()+": ----- "+en.getValue()+"次");
		 }

	}
}
/*
 //教师版
package com.shsxt.test04;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//统计单词出现的次数
 		

public class Test09 {
	public static void main(String[] args) {
		String str="this is a cat and that is a mouse where is the food and so on and so on";
		//1. 拆分数据成数组 根据空格
		String[] arr=str.split(" ");
		//2创建一个容器
		Map<String,Integer> maps=new HashMap<>();
		//3..遍历数组获取到每一个元素进行判断比对,存放到一个新的Map容器中
		for(String s:arr){
			if(maps.containsKey(s)){
				//把单词出现的次数+1  出现的次数不为第一次
				maps.put(s, maps.get(s)+1);
			}else{
				//当单词出现的次数为第一次
				maps.put(s,1);
			}
		}
		
		//4.获取到所有的key,遍历
		Set<String> sets=maps.keySet();
		for(String s:sets){
			System.out.println(s+"----->"+maps.get(s));
		}
	}
}
*/
  • 2.2 TreeMap实现类

  • 2.3 HashTable实现类

  • 2.3.1 Properties

 * Properties
 * 键值对  和Map很像---->Object ,但是P只存储String类型的键值对

package day14;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/*
 * Properties
 * 键值对  和Map很像---->Object ,但是P只存储String类型的键值对
 */
public class PropertiesTest07 {
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		Properties pro = new Properties();
		// pro.store(new FileOutputStream(new
		// File("D:/刘文旭/workspace/myProject/src/db.properties")),"db配置");
		pro.load(Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("db.properties"));
		pro.setProperty("123", "456");
		System.out.println(pro.get("123"));
	}
}
  • 3. Collections工具类

  • 3.1 定义

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

  • 3.2 方法

void sort(List) //对List容器内的元素排序,按照升序进行排序。

void shuffle(List) //对List容器内的元素进行随机排列

void reverse(List) //对List容器内的元素进行逆续排列

void fill(List, Object) //用一个特定的对象重写整个List容器

int binarySearch(List, Object)//采用折半查找的方法查找特定对象

package day14;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsTest06 {
	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.sort(ls);
		System.out.println(ls);
		Collections.fill(ls, "亚索");
		System.out.println(ls);
		System.out.println(Collections.binarySearch(ls, "李白"));
		
		GF g1 = new GF("nice", 1);
		GF g2 = new GF("good", 1);
		GF g3 = new GF("soso", 0);
		List<GF> list = new ArrayList<>();
		list.add(g1);
		list.add(g2);
		list.add(g3);
		System.out.println(list);//重写toString()
		
		Collections.reverse(list);
		System.out.println(list);
		
	}
}
class GF implements Comparable<GF>{
	private String body;
	private int sex;//1  男孩  0女孩
	
	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;
	}

	public GF(String body, int sex) {
		super();
		this.body = body;
		this.sex = sex;
	}


	@Override
	public String toString() {
		return "GF [body=" + body + ", sex=" + sex + "]";
	}

	@Override
	public int compareTo(GF o) {
		// TODO Auto-generated method stub
		return 0;
	}
	
}
  • 4. IO

  • 4.1 File

在Java中,Everything is Object!所以在文件中,也不例外!在Java中,可以用 File类来表示一个与硬盘上文件联系!!!

注意:

      1、File仅代表一个联系,可能文件存在,也可能不存在;

      2、这里的文件可以是文件,也可以是文件夹;

package day14.files;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/*
 * File文件
 * 	文件和目录路径名的抽象表示形式。
 * public class Fileextends Object implements Serializable, Comparable<File>
 */
public class FileDemo10 {
	public static void main(String[] args) {
		//创建一个File对象
		File file=new File("D:/shsxt.txt");
		//1.boolean canExecute() 测试应用程序是否可以存在
		System.out.println("测试应用程序是否可以存在:"+file.canExecute());
		//2.boolean canRead() 
		System.out.println("测试应用程序是否可读:"+file.canRead());
		//3.boolean canWrite()  
		System.out.println("测试应用程序是否可修改:"+file.canWrite()); //如果文件设置只读属性,就不可修改返回false
		//4.int compareTo(File pathname)  不区分大小写  如果相等返回0  <返回负数   >返回正数
		File file2=new File("D:/SHSXT.txt"); 
		System.out.println("测试两个文件对象比较:"+file.compareTo(file2)); 
		
		File f3=new File("D:/haha.txt"); 
		//5.boolean createNewFile()    当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。只能创建文件,不能创建文件夹
		try {
			System.out.println(f3.createNewFile());
		} catch (IOException e) {
			e.printStackTrace();
		}
		//6.static File createTempFile(String prefix, String suffix) 在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。 
		try {
			File f4=File.createTempFile("test",".rep");
			System.out.println("在临时文件夹中创建的空文件createTempFile()="+f4);  //C:\Users\Administrator\AppData\Local\Temp\test5148359668867489665.rep
		} catch (IOException e) {
			e.printStackTrace();
		}
		//7.static File createTempFile(String prefix, String suffix, File directory)  在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称
		File f5=new File("D:/"); 
		/*try {
			File f6=File.createTempFile("test",".rep",f5);
			System.out.println("在指定文件夹中创建的空文件createTempFile()="+f5);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		//8. boolean delete()  删除此抽象路径名表示的文件或目录。 
		System.out.println("删除文件:"+f3.delete());
//		System.out.println("删除文件夹:"+f5.delete());
		//9. boolean equals(Object obj)   测试此抽象路径名与给定对象是否相等。 
		System.out.println("判断两个文件对象是否相等equals:"+file.equals(file2)); //true
		//10.boolean exists() 测试此抽象路径名表示的文件或目录是否存在。 
		System.out.println("判断文件对象是否存在:"+file.exists()); //true
		/*
		 * 11. File getAbsoluteFile() 返回此抽象路径名的绝对路径名形式。   文件对象
		 * 12.String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串。   字符串
		 * 13.File getCanonicalFile()   返回此抽象路径名的规范形式。
		 */
		System.out.println("返回文件对象的绝对路径:"+file.getAbsoluteFile());   //D:\shsxt.txt
		System.out.println("返回文件对象的绝对路径:"+file.getAbsolutePath());   //D:\shsxt.txt
		try {
			System.out.println("返回文件对象的规范形式:"+file.getCanonicalFile());  D:\shsxt.txt
		} catch (IOException e) {
			e.printStackTrace();
		}   //D:\shsxt.txt
		/*
		 * 14 long getFreeSpace() 返回此抽象路径名指定的分区中未分配的字节数。 
		 */
		System.out.println("返回抽象路径名指定的分区中未分配的字节数:"+file.getFreeSpace());  //112872230912
		System.out.println("返回抽象路径名指定的分区中未分配的字节数:"+f5.getFreeSpace());  //112872230912
		/*
		 * 15.String getName()   返回由此抽象路径名表示的文件或目录的名称 
		 */
		System.out.println("返回文件或目录的名称 :"+f5.getName());
		/*
		 * 16. String getParent() 
          		返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。 
 		   17. File getParentFile() 
          		返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。 
           18.String getPath() 将此抽象路径名转换为一个路径名字符串。
		 */
		System.out.println("回此抽象路径名父目录的路径名字符串:"+file.getParent());
		System.out.println("将此抽象路径名转换为一个路径名字符串:"+file.getPath());
		
		// 19.boolean isAbsolute()  测试此抽象路径名是否为绝对路径名。 
		File f7=new File("haha.txt"); 
		System.out.println("测试此抽象路径名是否为绝对路径名:"+f7.isAbsolute());
		/*
		 *  20.boolean isDirectory() 
		          测试此抽象路径名表示的文件是否是一个目录。 
			21. boolean isFile() 
			          测试此抽象路径名表示的文件是否是一个标准文件。 
			22.boolean isHidden() 
			          测试此抽象路径名指定的文件是否是一个隐藏文件。 
			23.long lastModified() 
		          返回此抽象路径名表示的文件最后一次被修改的时间。 
		 */
		System.out.println("测试此抽象路径名最后一次被修改的时间:"+new SimpleDateFormat("yy-MM-dd hh:mm:ss").format(new Date(file.lastModified())));
		//24.long length() 返回由此抽象路径名表示的文件的长度。 
		System.out.println("测试此抽象路径名表示的文件的长度:"+file.length());
		/*
		 * 25. String[] list() 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。 
		 * 26.File[] listFiles()  返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件
		 */
		String[] ls=f5.list();
		for(String s:ls){
			System.out.println(s);
		}
		/*
		 * 27.boolean mkdir()  创建此抽象路径名指定的目录。   单层
		 * 28.boolean mkdirs() 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 
		 */
		File f8=new File("D:/bb/aa"); 
//		System.out.println("创建此抽象路径名指定的目录:"+f8.mkdir());  
		System.out.println("创建此抽象路径名指定的目录:"+f8.mkdirs());  
		//29.boolean renameTo(File dest) 重新命名此抽象路径名表示的文件。 
		File f9=new File("D:\\shsxtgood.txt");
		System.out.println("重命名:"+file.renameTo(f9)); 
		/*
		 *  29.boolean setExecutable(boolean executable) 
          		设置此抽象路径名所有者执行权限的一个便捷方法。 
		 *  30.boolean setReadable(boolean readable) 
          		设置此抽象路径名所有者读权限的一个便捷方法。 
		 *  31.boolean setWritable(boolean writable) 
          		设置此抽象路径名所有者写权限的一个便捷方法。 
            32.boolean setReadOnly() 
          		标记此抽象路径名指定的文件或目录,从而只能对其进行读操作。 
		 */
		File f10=new File("D:\\test.txt");  
//		System.out.println(f10.setWritable(false));
		System.out.println(f10.setReadOnly());
		//33.String toString() 返回此抽象路径名的路径名字符串。 
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值