Set与Map的基本用法

来源:互联网 发布:qq一键加群好友软件 编辑:程序博客网 时间:2024/05/29 09:58
package com.collection;


import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;


import org.junit.Test;


public class MapTest {
/**
* 默认情况下TreeSet要求集合中的元素必须实现Comparable接口
* Comparable接口中只有一个方法:根据方法返回值排序
* public int compareTo(T o):若返回0代表两个元素相等,若返回证书,代表当前元素大
* 若返回负数,代表当前元素小

* TreeSet会调用每个元素的compareTo()方法和集合中的每个已有的元素去比较
* 进而决定当前元素在集合中的位置
*/

@Test
public void testTreeSet(){
//1、创建一个TreeSet对象
TreeSet set=new TreeSet();
//2、由控制台输入5个学生的信息,并把每个学生的对象都放入到TreeSet中
Scanner scanner=new Scanner(System.in);
for(int i=0;i<5;i++)
{
System.out.print("Student["+(i+1)+"]'s name:");
String stuName=scanner.next();
System.out.print("Student["+(i+1)+"]'s score:");
int score=scanner.nextInt();
Person stu=new Person(stuName,score);
set.add(stu);
}
//遍历TreeSet打印即可
Iterator it=set.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

@Test
public void testTreeMap(){
Map map=new TreeMap();

  /* map.put("CC",new Person1("CC",12));
map.put("BB",new Person1("BB",12));
map.put("AA",new Person1("AA",12));
map.put("DD",new Person1("DD",12));
map.put("EE",new Person1("EE",12));*/

/*map.put(new Person("CC",12),"CC");
map.put(new Person("BB",11),"BB");
map.put(new Person("AA",15),"AA");
map.put(new Person("DD",9),"DD");
map.put(new Person("EE",32),"EE");
Iterator it=map.keySet().iterator();
while(it.hasNext()){
Object key=it.next();
Object val=map.get(key);
System.out.println(key+":"+val);
}*/
System.out.println("请选择排序方式:");
System.out.println("1、按分数升序 "+"2、按分数降序 "+"3、按名字升序 "+"4、按名字降序");
Scanner scanner=new Scanner(System.in);
final int flag=scanner.nextInt();
Comparator comparator=new Comparator(){


@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if(o1 instanceof Person1 && o2 instanceof Person1)
{
Person1 p1=(Person1) o1;
Person1 p2=(Person1) o2;
int scoreResult=p1.getAge()-p2.getAge();
int nameResult=p1.getName().compareTo(p2.getName());
if(flag==1){
return scoreResult;
}else if(flag==2){
return -scoreResult;
}else if(flag==3){
return nameResult;
}else{
return -nameResult;
}
}
throw new ClassCastException("不能转为person类型");
}

};
Map map2=new TreeMap(comparator);
map2.put(new Person1("CC",12),"CC");
map2.put(new Person1("BB",11),"BB");
map2.put(new Person1("AA",15),"AA");
map2.put(new Person1("DD",9),"DD");
map2.put(new Person1("EE",32),"EE");
Iterator it=map.keySet().iterator();
while(it.hasNext()){
Object key=it.next();
Object val=map2.get(key);
System.out.println(key+":"+val);
}
}

@Test
public void testLinkedHashMap(){
Map map=new LinkedHashMap();
map.put("CC",new Person1("CC",12));
map.put("BB",new Person1("BB",12));
map.put("AA",new Person1("AA",12));
map.put("DD",new Person1("DD",12));
map.put("EE",new Person1("EE",12));

Iterator it=map.keySet().iterator();
while(it.hasNext()){
Object key=it.next();
Object val=map.get(key);
System.out.println(key+":"+val);
}
}

/**
* HashSet由HashMap来定义
* 1. 在HashSet中维护了一个HashMap属性
* 2. 在调用HashSet的方法时,实际操作的是HashMap的对应方法
* 3. add(Object obj)实际上是把obj放入了map中
* public boolean add(E e)
* {  return map.put(e,PRESENT)==null;
* }
*/


@Test
public void testHashSet(){
Set set=new HashSet();
set.add(new Person1("AA",12));
set.add(new Person1("BB",13));
set.add(new Person1("CC",14));
set.add(new Person1("DD",15));
}

@Test
public void testMap(){

Map map=new HashMap();

//1. V put(K key,V value):返给一堆键值对
map.put("AA",new Person1("AA",12));
map.put("BB",new Person1("BB",12));
map.put("CC",new Person1("CC",12));
map.put("DD",new Person1("DD",12));
map.put("EE",new Person1("EE",12));

//2. boolean containsKey(Object key):Map中是否包含指定的key


//3. boolean containsValue(Object value):Map中是否包含指定的value

//4. Set<Map,Entry<k,v>> entrySet():得到键值对对应的Entry的Set
//需借助于泛型

//5. V get(Object key):根据key返回对应的value
Object obj=map.get("CC");
System.out.println(obj);

// 6. boolean isEmpty():检验Map是否为空
System.out.println(map.isEmpty());
//7. Set<k> keySet():返回Key对应的集合,set类型
//返回[AA, BB, CC, DD, EE]
Set keySet=map.keySet();
System.out.println(keySet);

//8. void clear:清空Map
//map.clear();
//System.out.println(map.size());


//9. void putAll(Map<? extends K,? extends V> m):放入一组键值对
Map map2=new HashMap();
map2.put("ONE","1111");
map2.put("TWO","222");
map2.put("THREE","333");
map.putAll(map2);
//10. V remove(Object key):移除指定键对应的键值对
map.remove("CC");

//11. int size():返回Map容量的大小
System.out.println(map.size());

//12. Collection<V> values():返回Value对应的集合
Collection values=map.values();
System.out.println(values);

//13. 对Map进行遍历
//13.1 遍历键的集合:keySet()
//13.2遍历值得集合:values()
//13.3得到键值对的集合

Iterator it= keySet.iterator();
while(it.hasNext()){
Object key=it.next();
Object val=map.get(key);
System.out.println(key+":"+val);
}
}

}


Person.java


package com.collection;


public class Person implements Comparable{
private String name;
private int age;

public Person(){}

public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}




/**
* @return the name
*/
public String getName() {
return name;
}


/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}


/**
* @return the age
*/
public int getAge() {
return age;
}


/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}


@Override
public String toString() {
return "Person [name=" + name + ", 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;
Person other = (Person) obj;
if (age != other.age)
return false;

return true;
}

@Override
public int compareTo(Object o) {
if(o instanceof Person){
Person person=(Person) o;
//return this.name.compareTo(person.name);
return -this.age+person.age;
}else{
throw new ClassCastException("不能转为Person类型");
}
}



}

0 0
原创粉丝点击