java hashset 排序set集合排序为啥o1-o2排序是从小到打的排序

Java中treeset怎么对字符串排序,对整形数值进行排序可以按照从小到大排序,若是对字符串排序该怎么排序_百度知道
Java中treeset怎么对字符串排序,对整形数值进行排序可以按照从小到大排序,若是对字符串排序该怎么排序
我有更好的答案
例:对加入&TreeSet的Student对象&&&实现Comparable接口,通过在Student中重写compareTo()方法确定该对象在TreeSet中的排序方式Student类如下123456789101112131415161718192021222324&&&class&Student&implements&Comparable&private&int&&//重写compareTo()方法&public&int&compareTo(Object&o){&Student&s&=&(Student)&o;&if&(this.age&&&s.age&)&return&-1;&else&if(s.age&==&this.age)&return&0;&else&return&1;&}当Student对象加入TreeSet时,是按年龄从小到大排序的。
网络工程师
String类的一个方法:compareTo(String str)功能按照字典顺序比较两个字符串
字典顺序是个神马?
按字典顺序比较两个字符串。该比较基于字符串中各个字符的 Unicode 值。按字典顺序将此 String 对象表示的字符序列与参数字符串所表示的字符序列进行比较。如果按字典顺序此 String 对象位于参数字符串之前,则比较结果为一个负整数。如果按字典顺序此 String 对象位于参数字符串之后,则比较结果为一个正整数。如果这两个字符串相等,则结果为 0;例如&f&.compareTo(&a&)返回一个正整数,那么说明f位于a后
本回答被提问者采纳
1条折叠回答
为您推荐:
其他类似问题
treeset的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。没有更多推荐了,
不良信息举报
举报内容:
关于TreeSet的排序问题
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!博客分类:
下文可以直接拿来运行使用,也可以直接下载附件包,编译直接运行就可以看到效果。
//ObjectSort
import java.util.ArrayLimport java.util.Cimport java.util.L
public class ObjectSort {
* @param args
public static void main(String[] args) {
* purpose: 根据对象的某个或者某些属性排序
* Java里面包含8个基本数据类型,分别是:boolean、byte、char、short、int、float、douboe、long
* 只比较非boolean和byte类型的属性,和大多数运用环境适应,如果有特殊要求,请自己修改。
* 使用时只要将对象属性列表和需要排序的List传入即可
List arrayDemo = new ArrayList();
Person p1 = new Person();
p1.setName("zhang san");
p1.setAge(22);
p1.setSalary(160);
Person p2 = new Person();
p2.setName("zhang san");
p2.setAge(22);
p2.setSalary(150);
Person p3 = new Person();
p3.setName("zhang san");
p3.setAge(25);
p3.setSalary(1900);
Person p4 = new Person();
p4.setName("zhao liu");
p4.setAge(25);
p4.setSalary(3000);
Person p5 = new Person();
p5.setName("liu qi");
p5.setAge(30);
p5.setSalary(2000);
arrayDemo.add(p1);
arrayDemo.add(p2);
arrayDemo.add(p3);
arrayDemo.add(p4);
arrayDemo.add(p5);
//*********开始比较********//
CommonComparator comparator = new CommonComparator();
System.out.println("1.sort by name, age and salary");
comparator.setFields_user(new String[]{"name","age","salary"});
Collections.sort(arrayDemo, comparator);
for(int i=0;i&arrayDemo.size();i++)
Person person = (Person)arrayDemo.get(i);
System.out.println("name:"+person.getName()+" age:"+person.getAge()+" salary:"+person.getSalary());
System.out.println("1.sort by name, age");
comparator.setFields_user(new String[]{"name","age"});
Collections.sort(arrayDemo, comparator);
for(int i=0;i&arrayDemo.size();i++)
Person person = (Person)arrayDemo.get(i);
System.out.println("name:"+person.getName()+" age:"+person.getAge()+" salary:"+person.getSalary());
//CommonComparator
import java.lang.reflect.Mimport java.math.BigDimport java.text.CollationKimport java.text.Cimport java.util.C
public class CommonComparator implements Comparator {
* 比较对象的属性用String[]的形式传过来
* 比较的对象一定要符合javaBean,即要有Set,Get方法
String[] fields_user =
public String[] getFields_user() {
return fields_
public void setFields_user(String[] fields_user) {
this.fields_user = fields_
* 定义排序规则
* 如果按照不止一个属性进行排序
* 这按照属性的顺序进行排序,类是sql order by
* 即只要比较出同位置的属性就停止
public int compare(Object obj1, Object obj2)
//没有属性,则不排序
if(fields_user == null || fields_user.length&=0)
return 2;//不比较
for(int i=0;i&fields_user.i++)
//return compareField(obj1,obj2,fields_user[i]);
if(compareField(obj1,obj2,fields_user[i])&0)
{//如果obj1的属性值大于obj2的属性值,则返回正数
}else if(compareField(obj1,obj2,fields_user[i])&0){
return -1;
* @param fieldName
* 根据属性名排序
private static int compareField(Object o1,Object o2,String fieldName)
Object value1 = getFieldValueByName(fieldName,o1);
Object value2 = getFieldValueByName(fieldName,o2);
//--字符串比较
if(value1 instanceof String)
String v1 = getFieldValueByName(fieldName,o1).toString();
String v2 = getFieldValueByName(fieldName,o2).toString();
Collator myCollator = Collator.getInstance();
CollationKey[] keys = new CollationKey[5];
keys[0] = myCollator.getCollationKey(v1);
keys[1] = myCollator.getCollationKey(v2);
return (keys[0].compareTo(keys[1]));
//--非比较属性不比较
else if("java.lang.Boolean".equals(value1.getClass().getName()) || "java.lang.Byte".equals(value1.getClass().getName()))
BigDecimal b1 = new BigDecimal(value1.toString());
BigDecimal b2 = new BigDecimal(value2.toString());
return b1.compareTo(b2);
} catch (Exception e)
System.out.println("-----------------------------------------------------------------------------");
System.out.println("---------对象的该属性不存在或者不允许在此安全级别上反射该属性,详情请查阅JAVA DOC--------");
System.out.println("-----------------------------------------------------------------------------");
e.printStackTrace();
return -1;
* fieldName 属性名
* obj 对象
* 反射获得该属性的值
private static Object getFieldValueByName(String fieldName,Object obj)
String Letter = fieldName.substring(0,1).toUpperCase();
String methodStr = "get"+Letter+fieldName.substring(1);
Method method = obj.getClass().getMethod(methodStr, new Class[]{});
Object value = method.invoke(obj, new Object[]{});
}catch(Exception e)
System.out.println("------------------------------------------------------");
System.out.println("---------该"+fieldName+"属性不存在----------------------");
System.out.println("------------------------------------------------------");
public class Person {
public Person(){}
public long getSalary() {
public void setSalary(long salary) {
this.salary =
public int getAge() {
public void setAge(int age) {
this.age =
public String getName() {
public void setName(String name) {
this.name =
下载次数: 70
浏览: 184618 次
来自: 武汉
还是你厉害啊~~ 这都被你发现了
那么反过来,能否在ftl页面里能否执行 setAttribut ...
困扰了我多日的问题,终于解决了
感谢,标记
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'没有更多推荐了,
不良信息举报
举报内容:
Java中按次序输出Set集合中的元素
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!今天随手了一段代码关于通过treeSet实现自动排序的功能,自己折腾了好久。
始终是存在这一些疑惑,后来和同学的交流和调试可以解释自动排序的基本原理:
通过可以通过两种方式实现自动排序:
package xyxysjxy.
import java.io.BufferedR
import java.io.BufferedW
import java.io.FileW
import java.io.IOE
import java.io.InputStreamR
import java.util.C
import java.util.I
import java.util.S
import java.util.TreeS
public class StudentInfoImport {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(
new FileWriter("f:\\student.txt"));
Set&Student& ss = StudentTools.getStudent();
Iterator&Student& is = ss.iterator();
while (is.hasNext()) {
Student student = (Student) is.next();
bw.write(student.toString());
bw.newLine();
bw.flush();
bw.close();
class Student{
public String getName() {
public void setName(String name) {
this.name =
public int getCn() {
public void setCn(int cn) {
public int getMath() {
public void setMath(int math) {
this.math =
public int getEn() {
public void setEn(int en) {
public int getSum() {
public void setSum(int sum) {
this.sum =
public Student(String name, int... is) {
this.name =
this.cn = is[0];
this.math = is[1];
this.en = is[2];
this.sum = cn + math +
public String toString() {
return "【name=" + name + "\tcn=" + cn + "\tmath=" + math + "\ten=" + en
+ "\tsum=" + sum + "】";
public boolean equals(Object obj) {
if (!(obj instanceof Student))
throw new ClassCastException("不能强制的转换");
Student s = (Student)
return s.name.equals(this.name) && s.sum == s.
public int hashCode() {
return sum * 78 + name.hashCode();
class StudentTools {
static Comparator&Student& com = new Comparator&Student&() {
public int compare(Student o1, Student o2) {
int sum = new Integer(o1.getSum()).compareTo(new Integer(o2.getSum()));
if (sum == 0)
return o1.getName().compareTo(o2.getName());
public static Set&Student& getStudent() throws IOException {
return getStudent(com);
public static Set&Student& getStudent(Comparator&Student& com)
throws IOException {
Set&Student& studentSet =
if (com == null)
studentSet = new TreeSet&Student&();
studentSet = new TreeSet&Student&(com);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String len = "";
while ((len = br.readLine()) != null) {
if (len.equals("over"))
String[] studentInfo = len.split(",");
Student s = new Student(studentInfo[0], new int[] {
Integer.parseInt(studentInfo[1]),
Integer.parseInt(studentInfo[2]),
Integer.parseInt(studentInfo[3]) });
// 当往HashSet中添加数据时,他会去找被添加对象的中实现了Comparable接口,
studentSet.add(s);
return studentS
package xyxysjxy.
import java.io.BufferedR
import java.io.BufferedW
import java.io.FileW
import java.io.IOE
import java.io.InputStreamR
import java.util.C
import java.util.I
import java.util.S
import java.util.TreeS
public class StudentInfoImport {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(
new FileWriter("f:\\student.txt"));
Set&Student& ss = StudentTools.getStudent();
Iterator&Student& is = ss.iterator();
while (is.hasNext()) {
Student student = (Student) is.next();
bw.write(student.toString());
bw.newLine();
bw.flush();
bw.close();
class Student implements Comparable&Student& {
public Student(String name, int... is) {
this.name =
this.cn = is[0];
this.math = is[1];
this.en = is[2];
this.sum = cn + math +
public String toString() {
return "【name=" + name + "\tcn=" + cn + "\tmath=" + math + "\ten=" + en
+ "\tsum=" + sum + "】";
public boolean equals(Object obj) {
if (!(obj instanceof Student))
throw new ClassCastException("不能强制的转换");
Student s = (Student)
return s.name.equals(this.name) && s.sum == s.
public int compareTo(Student o) {
int sum = new Integer(this.sum).compareTo(new Integer(o.sum));
if (sum == 0)
return this.name.compareTo(o.name);
public int hashCode() {
return sum * 78 + name.hashCode();
class StudentTools {
public static Set&Student& getStudent() throws IOException {
return getStudent(null);
public static Set&Student& getStudent(Comparator&Student& com)
throws IOException {
Set&Student& studentSet =
if (com == null)
studentSet = new TreeSet&Student&();
studentSet = new TreeSet&Student&(com);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String len = "";
while ((len = br.readLine()) != null) {
if (len.equals("over"))
String[] studentInfo = len.split(",");
Student s = new Student(studentInfo[0], new int[] {
Integer.parseInt(studentInfo[1]),
Integer.parseInt(studentInfo[2]),
Integer.parseInt(studentInfo[3]) });
&pre name="code" class="java"&// 当往HashSet中添加数据时,他会去找被添加对象的中实现了Comparable接口,
studentSet.add(s);
return studentS
通过上面的两段代码把这个执行的流程给大家讲解一下:
第一步:从控制台接收数值后封装到了一个student对象当中去。
其实在treeSet内部其实封装了一个TreeMap对象
当你调用了ADD方法时其实是调用了put方法。
&pre name="code" class="java"&while ((len = br.readLine()) != null) {
if (len.equals("over"))
String[] studentInfo = len.split(",");
Student s = new Student(studentInfo[0], new int[] {
Integer.parseInt(studentInfo[1]),
Integer.parseInt(studentInfo[2]),
Integer.parseInt(studentInfo[3]) });
&pre name="code" class="java"&
// 当往HashSet中添加数据时,他会去找被添加对象的中实现了Comparable接口,
studentSet.add(s);
return studentS
public TreeSet(Comparator&? super E& comparator) { this(new TreeMap&&(comparator)); }
第二步:首先他要进行检查。
这个三目运算符是这个意思:
首先他是判断你在newtreeset时候是否向其中传递了一个 comparator
对象,假如传递了那么直接调用你传进来的那个对象
但是你没有传递进来那么他就要做类型检查了,
检查的目的在与看你是否实现了Comparable假如实现了那么就调用你自身的实现接口的方法
&strong&&/strong&&pre name="code" class="java"&public V put(K key, V value) {
Entry&K,V& t =
if (t == null) {
compare(key, key); // type (and possibly null) check(L类型检查)
root = new Entry&&(key, value, null);
modCount++;
//其实在第一次存储对象时,所进行的比较是和自身比较 compare(key, key)
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable&? super K&)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); }
第三步: 当检查到你是实现了compare接口或是传递了一个compator对象时,
他会调用你自身的实现方法进行比较。
通过返回值:-1,0,1来判断你正要假如的值和treeset中的大小进行自动的排序的效果。
浏览: 11744 次
来自: 深圳
getGenericParameterTypesTest()虽 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'

我要回帖

更多关于 java set 自动排序 的文章

 

随机推荐