An instance of Java that is sorted by a field of an object stored in the list _java

Source: Internet
Author: User
Tags comparable

key point: implement the comparable class for the object stored in the list and rewrite its CompareTo () method

Bean:

Package CHC;
public class Stuvo implements comparable<stuvo>{
	private String ID;
	private String name;
	Private Integer age;
	Public Stuvo (string ID, string name, Integer age) {
		this.id=id;
		This.name=name;
		this.age=age;
	}
	public int CompareTo (Stuvo stu) {return
		This.name.compareTo (Stu.getname ());
	}
	Public String GetId () {return
		ID;
	}
	public void SetId (String id) {
		this.id = ID;
	}
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public Integer Getage () {return age
		;
	}
	public void Setage (Integer age) {
		this.age = age;
	}
}

Demo:

Package CHC;

Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Iterator;
Import java.util.List;

public class Arraylistsortdemo {public
	static void Main (string[] args) {
		list<stuvo> stulist=new Arraylist<stuvo> ();
		Stuvo stu=new Stuvo ("1", "H xiaoming", one);
		Stulist.add (Stu);
		
		Stu=new Stuvo ("2", "D-Bear",);
		Stulist.add (Stu);
		
		Stu=new Stuvo ("3", "A John", ten);
		Stulist.add (Stu);
		
		Stu=new Stuvo ("4", "B Dick");
		Stulist.add (Stu);
	
		Collections.sort (stulist);
		
		Iterator<stuvo> it =stulist.iterator ();
		while (It.hasnext ()) {
			System.out.println (It.next (). GetName ());}}}

Above this Java according to the list of objects stored in a field to sort the example is the small series to share all the content of everyone, hope to give you a reference, but also hope that we support cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.