集合的应用

集合的遍历和去除重复:

import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

public class Test01 {
	public static void main(String[] args) {

		Vector<Employee> vector = new Vector<Employee>();
		vector.add(new Employee("李四", 26, "办事员"));
		vector.add(new Employee("王五", 23, "经理"));
		vector.add(new Employee("王五", 23, "经理"));
		vector.add(new Employee("赵六", 36, "秘书"));
//		System.out.println("-----------方式一: foreach-------------");
//		for (Object object : vector) {
//			System.out.println(object);
//		}
//		
//		System.out.println("-----------方式二: toArray-------------");
//		Object[] objects = vector.toArray();
//		for (Object object : objects) {
//			System.out.println(object);
//		}
//		System.out.println("-----------方式三: 迭代器-------------");
//		Iterator<Employee> it = vector.iterator();
//		while (it.hasNext()) {
//			Object object = it.next();
//			System.out.println(object);
//		}
//		System.out.println("-----------方式四: 迭代器-------------");
//		for (Iterator<Employee> iterator = vector.iterator();iterator.hasNext(); ) {
//			Object object = iterator.next();
//			System.out.println(object);
//		}
//		System.out.println("-----------方式五: 普通for-------------");
//		for (int i = 0; i < vector.size(); i++) {
//			System.out.println(vector.get(i));
//		}
//		System.out.println("-----------方式六: 列表迭代器 正向遍历-------------");
//		ListIterator<Employee> listIterator = vector.listIterator();
//		while (listIterator.hasNext()) {
//			System.out.println(listIterator.next());
//		}
//		System.out.println("-----------方式七: 列表迭代器 逆向遍历-------------");
//		for (ListIterator<Employee> lit = vector.listIterator(vector.size()); lit.hasPrevious();) {
//			System.out.println(lit.previous());
//		}
//		System.out.println("-----------方式八: Vector所特有的遍历方式 旧版迭代器-------------");
//		Enumeration<Employee> elements = vector.elements();
//		while (elements.hasMoreElements()) {
//			System.out.println(elements.nextElement());
//		}

		System.out.println("-----------方式一:去除重复元素-------------");
		// 创建一个新的集合  (1)如果比较的是系统类,String 不需要重写equals方法
		//(2)如果比较的是自定义对象,需要自己根据需求重写equals方法
		Vector<Employee> newList = new Vector<Employee>();
		for (Object object : vector) {
			Employee employee = (Employee) object;
			if (!newList.contains(employee)) {
				newList.add(employee);
			}
		}

		for (Object object : newList) {
			System.out.println(object);
		}
		System.out.println("-----------方式二:去除重复元素-------------");
		// 选择排序思想去除重复元素
		for (int i = 0; i < vector.size() - 1; i++) {
			for (int j = i + 1; j < vector.size(); j++) {
				if (vector.get(i).equals(vector.get(j))) {
					vector.remove(j);
					j--;
				}
			}
		}

		for (Object object : vector) {
			System.out.println(object);
		}

	}
}

class Employee {
	private String name;
	private int age;
	private String position;

	public Employee() {
		super();
	}

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

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((position == null) ? 0 : position.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;
		Employee other = (Employee) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (position == null) {
			if (other.position != null)
				return false;
		} else if (!position.equals(other.position))
			return false;
		return true;
	}

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

	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 String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

}


随机数的生成:

import java.util.HashSet;


/*
 * 	六、获取10个1-20之间的随机数,要求不能重复
 */

public class Task07 {

	public static void main(String[] args) {

		//定义一个集合把随机数存储  Hashset 无序的
		HashSet<Integer> list = new HashSet<Integer>();
		//定义一个集合把随机数存储  TreeSet 有序的
		//TreeSet<Integer> list = new TreeSet<Integer>();
		//调用方法把随机数生成
		while (list.size() < 10) {
			list.add(getRandomNumber(1, 20));
		}
		//遍历集合,获得随机数
		for (Integer it : list) {
			System.out.println(it);
		}

	}
//先写获得随机数的方法
	public static int getRandomNumber(int start, int end) {
	//随机数公式  Math.random() * (end - start + 1) + start
		return (int) (Math.random() * (end - start + 1) + start);
	}
}

集合的排序:

import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
import java.util.Scanner;
import java.util.TreeSet;

/*
 * 	八、键盘录入5个学生信息(姓名,年龄,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台
 *	注:总分相同等情况下按照语文成绩排序,其次是数学成绩、英语成绩、年龄、姓名
 */

public class Task09 {

	public static void main(String[] args) {

		TreeSet<Student> list = new TreeSet<Student>(new Comparator<Student>() {

			@Override
			public int compare(Student s1, Student s2) {
				//注:总分相同等情况下按照语文成绩排序,其次是数学成绩、英语成绩、年龄、姓名
				Collator c = Collator.getInstance(Locale.CHINESE);
				double num1 = s1.getTotalScore() - s2.getTotalScore();
				double num2 = (num1 == 0) ? s1.getChineseAch() - s2.getChineseAch() : num1;
				double num3 = (num2 == 0) ? s1.getMathematicsAch() - s2.getMathematicsAch() : num2;
				double num4 = (num3 == 0) ? s1.getEnglishAch() - s2.getEnglishAch() : num3;
				double num5 = (num4 == 0) ? s1.getAge() - s2.getAge() : num4;
				double num6 = (num5 == 0) ? c.compare(s1.getName(), s2.getName()) : num5;
				return num6 < 0 ? -1 : ((num6 == 0) ? 0 : 1);
			}
		});
		
		for (int i = 1; i <= 5; i++) {
			@SuppressWarnings("resource")
			Scanner input = new Scanner(System.in);
			System.out.print("请输入第" + i + "个学生的姓名:");
			String name = input.next();
			System.out.print("请输入第" + i + "个学生的年龄:");
			Integer age = input.nextInt();
			System.out.print("请输入第" + i + "个学生的语文成绩:");
			Double ChineseAch = input.nextDouble();
			System.out.print("请输入第" + i + "个学生的数学成绩:");
			Double MathematicsAch = input.nextDouble();
			System.out.print("请输入第" + i + "个学生的英语成绩:");
			Double EnglishAch = input.nextDouble();
			list.add(new Student(name, age, ChineseAch, MathematicsAch, EnglishAch));
		}

		for (Student student : list) {
			System.out.println(student);
		}
	}
}

使用LinkedList或者ArrayDeque模拟栈结构和队列结构的集合:

```Java
import java.util.AbstractCollection;
import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.LinkedList;

/*
 * 使用LinkedList或者ArrayDeque模拟栈结构和队列结构的集合
 */
public class Practicec02 {
	public static void main(String[] args) {
		MyStack<String> stack = new MyStack<>();
		stack.push("abc");
		stack.push("efg");
		stack.push("hij");
		for (String s : stack) {
			System.out.println(s);
		}
		
		System.out.println("--------------------------");

		MyQueue<String> queue = new MyQueue<String>();
		queue.offer("abc1");
		queue.offer("abc2");
		queue.offer("abc3");

		while (!queue.isEmpty()) {
			System.out.println(queue.poll());
		}
	}
}

//使用ArrayDeque模拟队列结构的集合
class MyQueue<E> extends AbstractCollection<E> {

	private LinkedList<E> list;

	public MyQueue() {
		list = new LinkedList<>();
	}

	// 入队
	public void offer(E e) {
		list.addLast(e); // [a,b,c]
	}

	// 出队
	public E poll() {
		return list.removeFirst();
	}

	// 获取对头元素
	public E peek() {
		return list.peekFirst();
	}

	public boolean isEmpty() {
		return list.isEmpty();
	}

	@Override
	public Iterator<E> iterator() {
		return list.iterator();
	}

	@Override
	public int size() {
		return list.size();
	}
}

//使用LinkedList模拟栈结构的集合
class MyStack<E> extends AbstractCollection<E> {

	private LinkedList<E> list;

	public MyStack() {
		list = new LinkedList<>();
	}

	// 入栈
	public void push(E e) {
		list.addFirst(e); // [c,b,a]
	}

	// 弹栈
	public E pop() {
		try {
			return list.removeFirst();
		} catch (Exception e) {
			throw new EmptyStackException();
		}
	}

	// 获取栈顶元素
	public E peek() {
		return list.peekFirst();
	}

	public boolean isEmpty() {
		return list.isEmpty();
	}

	@Override
	public Iterator<E> iterator() {
		return list.iterator();
	}

	@Override
	public int size() {
		return list.size();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值