以前对java的Set集合运用的不是很多,平时做项目什么的,只记得Hibernate关系实体映射中OneToMany和ManyToMany中,比如Set<User> users = new HashSet<User>();
原来set过滤相同对象真的很方便,以及对象按照自己指定的方法排序,这些都挺实用的。
描述
1.按照编号从小到大排序
2.对于编号相等的长方形,按照长方形的长排序;
3.如果编号和长都相同,按照长方形的宽排序;
4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
-
输入
- 第一行有一个整数 0<n<10000,表示接下来有n组测试数据;
每一组第一行有一个整数 0<m<1000,表示有m个长方形;
接下来的m行,每一行有三个数 ,第一个数表示长方形的编号,
第二个和第三个数值大的表示长,数值小的表示宽,相等
说明这是一个正方形(数据约定长宽与编号都小于10000);
输出 - 顺序输出每组数据的所有符合条件的长方形的 编号 长 宽 样例输入
-
1 8 1 1 1 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1
样例输出
1 1 1 1 2 1 1 2 2 2 1 1 2 2 1
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); //有n个测试数据 while(n-- > 0){ //接收有几个矩形 int count = Integer.parseInt(sc.nextLine());//count=8 Set<Rect> set = new HashSet<Rect>(); for(int i=0;i<count;i++){ String rectStr = sc.nextLine();//1 2 1 String[] rectS = rectStr.split(" "); //计算出矩形的长和宽 int length = Math.max(Integer.parseInt(rectS[1]), Integer.parseInt(rectS[2])); int width = Math.min(Integer.parseInt(rectS[1]), Integer.parseInt(rectS[2])); Rect rect = new Rect(Integer.parseInt(rectS[0]), length, width); set.add(rect); } List<Rect> list = new ArrayList<Rect>(set); Collections.sort(list, new MyComparator()); for(Rect rect : list){ System.out.println(rect.id+" "+rect.length+" "+rect.width); } } } } //定义我自己的比较器 class MyComparator implements Comparator<Rect>{ /** * 两个矩形,若果矩形id不同,就按照矩形升序排列 * 如果矩形id同,就按照矩形的长升序排列 * 如果矩形id同,并且矩形的长同,就按照矩形的宽升序排序 */ @Override public int compare(Rect o1, Rect o2) { if(o1.id != o2.id){ return o1.id - o2.id; }else if(o1.length != o2.length){ return o1.length - o2.length; }else{ //说明id和length也相同 return o1.width - o2.width; } } } class Rect{ int id; int length;//矩形的长 int width;//矩形的宽 public Rect(int id,int length,int width){ this.id = id; this.length = length; this.width = width; } //这里重新equals方法和hashCode,用id和length和width来标识 @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + length; result = prime * result + width; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rect other = (Rect) obj; if (id != other.id) return false; if (length != other.length) return false; if (width != other.width) return false; return true; } }