java之Set集合的HashSet类,TreeSet类的应用

实现Set接口的HashSet类

基于HashCode实现元素不重复,当存入元素的哈希吗相同时,会调用equals进行确认,如结果为true,则拒绝后者存入。

HashMap里面的Key允许为NULL,元素不可重复,无序,线程不安全。

import java.util.*;
public class Demo01 {

	public static void main(String[] args) {
		// 实现set接口的类
		
		
		Set <Game>set =new HashSet<Game>();
		
		Game hero1 =new Game("Timo",60,700);
		Game hero2 =new Game("盖伦",65,800);
		Game hero3 =new Game("诺克",62,750);
		
		
		set.add(hero1);
		set.add(hero2);
		set.add(hero3);
		set.add(null);//可以为null
		
		System.out.println(set.size());
		for(Game a1 : set) {//for
			
			System.out.println(a1);
			
		}
		
		System.out.println("___________________________________________");
		
		Iterator inerator = set.iterator();//使用迭代器遍历
		hero1.setPowr(99999);
		hero1.setLife(99999);
		for(Iterator it = set.iterator();it.hasNext();System.out.println(it.next())) {
			
		}
				
		
		
	}

}
class Game{
	
		private String name;
		
		private int powr;
		
		private int life;
		public Game() {
			
		}
		public  Game(String name,int powr,int life) {
		
			this.name=name;
			this.powr=powr;
			this.life=life;
			
	}
		@Override
		public String toString() {
			return "Game [name=" + this.name + ", powr=" + this.powr + ", life=" + this.life + "]";
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getPowr() {
			return powr;
		}
		public void setPowr(int powr) {
			this.powr = powr;
		}
		public int getLife() {
			return life;
		}
		public void setLife(int life) {
			this.life = life;
		}
		
	
	
	
}

实现Set接口的TreeSet类

 HashMap里面的Key不允许为NULL,元素不可重复,无序,线程不安全。

import java.util.Set;
import java.util.TreeSet;

import com.qianfeng.ls.am.first.Person;

import java.util.Iterator;
import java.util.HashSet;

public class Demo02 {

	public static void main(String[] args) {
		// set接口的实现者TreeSet
	
		
		
		Set <Hero> set1 =new TreeSet <Hero>();//Hero类型的泛型Set集合
		Iterator it =set1.iterator();//创建迭代器对象
		
		Hero h1 =new Hero("Timo",666);
		Hero h2 =new Hero("Gailun",999);
		Hero h3 =new Hero("OK",100);
	
		set1.add(h1);
		set1.add(h2);
		set1.add(h3);
		System.out.println(set1.size());
		for(Iterator its =set1.iterator();its.hasNext();System.out.println(its.next())) {
			
			
		}
		
	}

}
@SuppressWarnings("rawtypes")
class Hero implements Comparable{
	
	private String name;
	private int age;
	
	
	public int compareTo(Object page){
		
		Hero ho1 =(Hero)page;
		
		return this.name.compareTo(ho1.name) ;
		
	}
	public Hero(){
		
	}
	public Hero(String name,int age) {
		
		this.age=age;
		this.name=name;
		
		
		
	}
	@Override
	public String toString() {
		return "Hero [name=" + name + ", 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;
	}
	
	
	
}
发布了22 篇原创文章 · 获赞 0 · 访问量 384

猜你喜欢

转载自blog.csdn.net/weixin_44657829/article/details/104701213