java 集合框架 Set Map List

set:

特点:无序的,长度可变的,不可重复的。

 

 

HashSet 的实现

对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层采用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单。

底层数据结构是 hash 表。

 

HashSet 保证元素的唯一性是通过元素的两个方法,hashCode 和 equals 来完成。

    -----如果元素的 HashCode 值相同,才会判断 equals 是否为true。

    -----如果元素的 HashCode 值不同,不会调用equals。

    -----注意:对于判断元素是否存在,以及删除等操作,依赖的方法是 hashcode 和 equals 方法。

 

 

import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo {
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  HashSet hs = new HashSet();
  // hs.add(new Students("v7","java"));
  hs.add(new Students("V7S", "java"));
  System.out.println(hs.contains(new Students("V7", "java")));
  Iterator iterator = hs.iterator();
  while (iterator.hasNext()) {
   Students ss = (Students) iterator.next();
   System.out.println(ss.getName() + "----" + ss.getBook());
  }
 }
}
class Students {
 public String name;
 public String book;
 @Override
 public boolean equals(Object o) {
  if (this == o) {
   return true;
  }
  if (o.getClass() == Students.class) {
   Students n = (Students) o;
   return n.book.equals(book); //只判断 book 字段
   //return n.book.equals(book) && n.name.equals(name);
  }
  return false;
 }
 @Override
 public int hashCode() {
  // TODO Auto-generated method stub
  return this.book.hashCode();
 }
 public Students(String name, String book) {
  // TODO Auto-generated method stub
  this.name = name;
  this.book = book;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getBook() {
  return book;
 }
 public void setBook(String book) {
  this.book = book;
 }
}


 

 

TreeSet 是依靠 TreeMap来实现的。
TreeSet 是一个有序集合,TreeSet 中的元素将按照升序排列,缺省是按照自然排序进行排列,意味着TreeSet 中的元素要实现Comparable接口。或者有一个自定义的比较器。
我们可以在构造TreeSet对象时,传递实现 Comparator 接口的比较器对象。

 

/**
 *
 *TreeSet:可以对 Set 集合中的元素进行排序。
 *   底层数据结构二叉树
 *   保证元素的唯一性的依据。
 *   compareTo 方法 return 0
 *   
 *   TreeSet 排序的第一种方式:让元素自身具备比较性
 *   元素需要实现 Compareable 接口,覆写 compareTo 方法。
 *   
 *
 *   TreeSet 的第二种排序方式:
 *   当元素自身不具备比较性时,或者具备的比较性不是所需要的。
 *   这时就需要让集合自身具备比较性。
 *
 */

 

TreeSet 排序的第一种方式:
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet ts = new TreeSet();
		ts.add(new Student("v1", 10));
		ts.add(new Student("v2", 11));
		ts.add(new Student("v3", 12));
		ts.add(new Student("v4", 13));
		ts.add(new Student("v1", 11));
		
		Iterator ite = ts.iterator();
		
		while(ite.hasNext()){
			Student st = (Student)ite.next();
			System.out.println(st.getName()+"<-->"+st.getAge());
		}
	}
	
}

class Student implements Comparable{ //实现 Comparable 接口,强制让元素具备比较性
	private String name;
	private int age;
	
	public Student(String name,int age) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.age = age;
	}
	
		
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		if(!(o instanceof Student))
			throw new RuntimeException("不是学生类对象!");
		Student stu = (Student)o;
		System.out.println(stu.age+"=========compareTo()====>"+stu.name);
		//主要因素
		if(this.age > stu.age){
			return 1;
		}else if(this.age == stu.age){
			//次要因素
			return this.name.compareTo(stu.name);
		}
		return -1;
	}
	
	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;
	}

}

TreeSet 的第二种排序方式:TreeSet 的第二种排序方式:
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet ts = new TreeSet(new myCompa());
		ts.add(new Student("v1", 10));
		ts.add(new Student("v2", 11));
		ts.add(new Student("v3", 12));
		ts.add(new Student("v4", 13));
		ts.add(new Student("v1", 11));
		
		Iterator ite = ts.iterator();
		
		while(ite.hasNext()){
			Student st = (Student)ite.next();
			System.out.println(st.getName()+"<-->"+st.getAge());
		}
	}
	
}


class myCompa implements Comparator{
	@Override
	public int compare(Object o1, Object o2) {
		Student st1 = (Student)o1;
		Student st2 = (Student)o2;
		
		int num = st1.getName().compareTo(st2.getName());
		if(num == 0){
			return new Integer(st1.getAge()).compareTo(new Integer(st2.getAge()));
		}
		return num;
	}
	
}


class Student{
	private String name;
	private int age;
	
	public Student(String name,int age) {
		// TODO Auto-generated constructor stub
		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;
	}

}

 

 

 

 


  * Map集合 :key -value键值对 , 保证键的唯一性
   *
   * HashMap 集合 .put() 方法添加元素的时候
   * 当该键不存在的时候,也会返回 null,
   * 当键存在的时候,会返回旧值,并将新值替换旧值.
   *
   * 由于 HashMap 和 HashTable 有一处不同:
   *  HashMap : 底层是 hash 表数据结构,允许插入 null 键 , null 值. jdk 1.2 效率高    , 线程不安全
   *  HashTable : 底层是 hash 表数据结构, 不允许插入 null 键, null 值. jdk 1.0   效率低  , 线程安全
   *
   * 所以需要注意,存在重复的时候,第二次 put 也会返回 一个 null

 

package com.v7test.setcoll;

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 HashMapDemo {
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<String, String>();
		
		/**
		 * Map 集合 : key - value 键值对 , 保证键的唯一性
		 * 
		 * HashMap 集合 .put() 方法添加元素的时候
		 * 当该键不存在的时候,也会返回 null,
		 * 当键存在的时候,会返回旧值,并将新值替换旧值.
		 * 
		 * 由于 HashMap 和 HashTable 有一处不同:
		 * 	HashMap : 允许插入 null 键 , null 值. jdk 1.2 效率高    , 线程不安全
		 * 	HashTable : 不允许插入 null 键, null 值. jdk 1.0   效率低  , 线程安全
		 * 
		 * 所以需要注意,存在重复的时候,第二次 put 也会返回 一个 null 
		 */
		System.out.println("add 'a'==>"+map.put("a", "A"));
		System.out.println("add 'a'==>"+map.put("a", "F"));
		
		/**
		 * 添加
		 */
		map.put("b", "B");
		map.put("c", "C");
		map.put("d", "D");
		map.put(null,null);
		System.out.println("map key = null value : ==>"+map.get(null));
		System.out.println("remove=>"+map.remove("d"));
		System.out.println("map==>"+map);
		
		/**
		 * 判断
		 */
		if(map.containsKey("a") && map.containsValue("C")){
			System.out.println("contains===!!!");
		}
		
		Collection<String> values = map.values();
		//返回此映射中包含的值的 Collection 视图。
		//也就是返回所有的 map --> value
		System.out.println("values==>"+values);
		Object[] array = values.toArray();
		for (Object object : array) {
			System.out.println("object==------>>>>>"+object);
		}
		//获取
		
		//one method
		Set<String> keyset = map.keySet();
		Iterator<String> it = keyset.iterator();
		while(it.hasNext()){
			String key = it.next();
			String value = map.get(key);
			System.out.println(key+"-"+value);
		}
		
		//two method
		Set<Map.Entry<String, String>> entrySet = map.entrySet();
		Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
		while(iterator.hasNext()){
			Map.Entry<String, String> entry = iterator.next();
			System.out.println("key="+entry.getKey()+",value="+entry.getValue());
		}
		
		//two method (1)
		Set<Entry<String, String>> entry = map.entrySet();
		Iterator<Entry<String, String>> iterr = entry.iterator();
		while(iterr.hasNext()){
			Entry<String, String> ent = iterr.next();
			System.out.println("key="+ent.getKey()+",value="+ent.getValue());
		}
	}
}


 

 

 TreeMap:(和 TreeSet 类似);

 

package com.v7test.setcoll;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

/**
 * 
 * @author V7
 * 	
 *
 */
class TreeMapDemo {
	public static void main(String[] args) {
		TreeMap<User, String> tm = new TreeMap<User, String>(new myCompare());//构造一个新的、空的树映射,该映射根据给定比较器进行排序。
		tm.put(new User("zhang", 123), "No1");
		tm.put(new User("wang", 456), "No2");
		tm.put(new User("cheng", 789), "No3");
		tm.put(new User("li", 345), "No4");
		tm.put(new User("tang", 234), "No5");
		
		Set<Entry<User, String>> es = tm.entrySet();
		
		Iterator<Entry<User, String>> it = es.iterator();
		while(it.hasNext()){
			Entry<User, String> nv = it.next();
			User key = nv.getKey();
			String value = nv.getValue();
			System.out.println("name=:"+key.getName()+"--password=:"+key.getPassword()+"--map-value=:"+value);
		}
	}
}

/**
 * 
 * @author V7
 * 自定义比较器
 * 	通过姓名排序
 *
 */
class myCompare implements Comparator<User>{

	@Override
	public int compare(User o1, User o2) {
		// TODO Auto-generated method stub
		int num = o1.getName().compareTo(o2.getName());
		if(num==0)
			return new Integer(o1.getPassword()).compareTo(new Integer(o2.getPassword()));
		return num;
	}
	
}

/**
 * 
 * @author V7
 * 	实现 Comparable 为了让 User 具备自然顺序
 * 		通过,password 排序
 *
 */
class User implements Comparable<User>{
	private String name;
	
	private int password;
	
	public User(String name,int password) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.password = password;
	}
	
	@Override
	public int compareTo(User o) {
		// TODO Auto-generated method stub
		int num = new Integer(this.password).compareTo(new Integer(o.password));
		if(num==0)
			this.name.compareTo(o.name);
		return num;
	}

	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		if(!(obj instanceof User))
			throw new ClassCastException("类型不匹配");
		User user = (User)obj;
		
		return this.name.equals(user.getName()) && this.password == user.getPassword();
	}
	
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return name.hashCode()+password*34;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		this.password = password;
	}
}


 

 List 集合:

 

package com.shanghai.list;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class ListDemo{
	public static void main(String[] args){
		sortDemo();
	}
	
	public static void sortDemo(){
		List<String> list = new ArrayList<String>();
		
		list.add("abcd");
		list.add("vbd");
		list.add("z");
		list.add("hj");

		Collections.sort(list,new MyComp());//集合工具类,排序,实现Comparator 倒序
		sop(list);
		Collections.sort(list,Collections.reverseOrder(new MyComp())); //Collections.reverseOrder(cmp) , 返回一个比较器,它强行逆转指定比较器的顺序。
		sop(list);
		
		//int index = Collections.binarySearch(list, "z");//二分搜索法
		int index = halfSearch(list, "z");//自定义二分搜索法
		sop(index);
		Collections.replaceAll(list, "z", "xxxxxxxxxxxxxx");//替换一个值
		sop(list);
		Collections.reverse(list); //反转
		sop(list);
		Collections.fill(list, "pp");//替换所有
		sop(list);
	}
	
	public static int halfSearch(List<String> list,String key){
		int min,max,mid;
		max = list.size() - 1;
		min = 0;
		while(min<=max){
			mid = (max + min) >> 1;
			
			String str = list.get(mid);
			
			int num = str.compareTo(key);
			
			if(num>0){
				max = mid - 1;
			}else if(num < 0){
				min = mid + 1;
			}else{
				return mid;
			}
		}
		return -min-1;
	}
	
	public static void sop(Object obj){
		System.out.println(obj);
	}
}

class MyComp implements Comparator<String>{

	@Override
	public int compare(String o1, String o2) {
		return o2.compareTo(o1);//倒序
	}
	
}


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值