Your location:Tech News>News>Script>Several methods to achieve certain properties of Java objects stored in accordance sorting objects example

Latest News

Several methods to achieve certain properties of Java objects stored in accordance sorting objects example

Author:fsadmin

Views:

  This article describes several examples of methods stored in Java object and press the object an attribute to sort.Share to you for your reference, as follows:

  In programming, often occur on certain kinds of objects are sorted according to the custom of certain properties, such as: student objects sorted according to age size.

  One method is to age singled sorted, and the order of the array ages deposit a weight students.But this is too complicated, and there is no better way to do that?

  There are drop ~

  First, you can achieve while adding side sorting, need to use TreeSet.

  The second, with an array of objects are stored, a property but without a separate extraction lined up and then re-deposit, but rearrange the order of a comparator in the original array.Need to use Arrays.sort (arr, comparator).

  Third, storage objects are subclasses of the set of classes list, and sorting.Need to use Collections.sort (list, comparator).

  The following were discussed:

  A, TreeSet

  create:

  No.

  Description constructor

  1

  TreeSet ()

  This empty tree constructor configured to set, in the natural ordering of its elements in ascending.

  2

  TreeSet (set of c)

  This set of spanning tree constructor, which contains the set of elements c.

  3

  TreeSet (Comparator comp)

  This constructor configured to set an empty tree, ordered according to a given comparator.

  increase:

  The specified element to this set if it is not already there.

  All the elements are added in to join this group in the specified collection.

  delete:

  Removes the specified element from this group, if it exists.

  Removes all elements from this group.

  check:

  In return for this sort set, or empty element, if this sort its elements using natural Comparison.

  If this set contains the specified element Returns .

  If this set contains no elements Returns .

  Returns an iterator set in ascending order of element.

  Returns the number of the set (its cardinality) elements.

  Traverse: traverse through the iterator.

  Iterator it = treeset.iterator ();

  while (it.hasNext ()) {

  // current node operation.

  }

  Code:

  TreeSet is an ordered collection, TreeSet elements in the ascending order.

  When TreeSet storage objects can be sorted, which has a default sorting method Integer, String sorted has a default storage class object ,, and when there is no custom order, the sorting algorithm need to customize.

  If you want an object into a custom class TreeSet sort, or of int, String objects you want to define your own sorting method, there are two ways:

  The first sort of way:

  Let the element itself has a comparative.Let elements implement the Comparable interface, covering compareTo method, the comparison algorithm defined in the method, depending on the size relationship, positive negative or zero return.When using TreeSet object stored inside () method is called automatically add the compareTo () methods were compared, based on the comparison is stored in the form of binary tree.

  The second sort of way:

  Custom comparator. Comparator define a class that implements the interface, the compare method coverage.The Comparator interface subclass object passed to the constructor set TreeSet.

  The first: Comparable interface implemented when the class definition, the definition of their comparison algorithm.

  Here to Person class, for example, the names and ages as object properties, deposited into treeset in accordance with the age of liters / descending save.

  public class TreeSetTest {

  public static void main (String [] args) {

  TreeSet people = new TreeSet ();

  people.add (new Person ( "Bob", 20));

  people.add (new Person ( "Zhang", 30));

  people.add (new Person ( "Liu", 18));

  people.add (new Person ( "Kobayashi", 17));

  people.add (new Person ( "Liu", 35));

  Iterator = people.iterator ();

  while (it.hasNext ()) {

  System.out.println (it.Next ());

  }

  }

  }

  When the class Person implements Comparable {// definition of classes, interfaces achieve more

  String name;

  int age;

  public Person () {

  }

  public Person (String name, int age) {

  this.name = name;

  this.age = age;

  }

  public String toString () {

  return "Name:" + name + ", Age:" + age;

  }

  public int compareTo (Object o) {

  Person curr = (Person) o;

  // int result = this.age

  int result = this.age> curr.age?1:(this.age==curr.age?0: -1); // ascending order: the newly inserted node and the comparison of the current layer node attribute comparison, a large return, continue down one comparator

  if (result == 0) {

  result = this.name.compareTo (curr.name); // age same, the places to arrange the names alphabetically.As mentioned, int, string type is the default arrangement algorithm, so here directly

  }

  return result;

  }

  }

  The second: Comparator interface implementation class definitions (comparator), the comparison algorithm defined in the class in object.When creating Treeset objects pass in the comparator.

  public class TreeSetTest {

  public static void main (String [] args) {

  TreeSet people = new TreeSet (new MyComparator ()); // the comparator object as the constructor argument TreeSet

  people.add (new Person ( "Bob", 20));

  people.add (new Person ( "Zhang", 30));

  people.add (new Person ( "Liu", 18));

  people.add (new Person ( "Kobayashi", 17));

  people.add (new Person ( "Liu", 35));

  Iterator = people.iterator (); // iterative traversal treeset

  while (it.hasNext ()) {

  System.out.println (it.Next ());

  }

  }

  }

  class Person {

  String name;

  int age;

  public Person () {

  }

  public Person (String name, int age) {

  this.name = name;

  this.age = age;

  }

  public String toString () {

  return "Name:" + name + ", Age:" + age;

  }

  }

  class MyComparator implements Comparator {// implement Comparator interface, custom comparator, comparison algorithm implemented compare method defined

  public int compare (Object o1, Object o2) {

  Person p1 = (Person) o1;

  Person p2 = (Person) o2;

  int result = p1.age

  // int result = p1.age

  if (result == 0) {

  result = p1.name.compareTo (p2.name);

  }

  return result;

  }

  }

  Second, the object with the array of storage, to change the sort comparator () method of sorting.

  Array itself has a default sorting method, there is a default sort for basic type int, string, etc. () method.And for sorting class object, you can give sort () method passed into a comparator object, given its sorting algorithm.

  public class ArraysTest {

  public static void main (String [] args) {

  Person [] people = new Person [5];

  people [0] = (new Person ( "Bob", 20));

  people [1] = (new Person ( "Zhang", 30));

  people [2] = (new Person ( "Liu", 18));

  people [3] = (new Person ( "Kobayashi", 17));

  people [4] = (new Person ( "Liu", 35));

  Arrays.sort (people, new MyCompare ()); // object passed in a comparator, that the array of comparators as defined by rules to sort

  for (Person i: people) {

  System.out.println (i);

  }

  }

  }

  class Person {

  String name;

  int age;

  public Person () {

  }

  public Person (String name, int age) {

  this.name = name;

  this.age = age;

  }

  public String toString () {

  return "Name:" + name + ", Age:" + age;

  }

  }

  class MyCompare implements Comparator{// definition of comparator

  public int compare (Person o1, Person o2) {

  int result;

  if (o1.age> o2.age) {

  result = 1;

  }

  else if (o1.age

  result = -1;

  }

  else {

  result = 0;

  }

  return result;

  }

  }

  Third: list of sub-categories: Vector, ArrayList objects are stored, call Collections.sort (list, comparator) sorting method.

  public class CollectionsTest {

  public static void main (String [] args) {

  Vector people = new Vector<>();//用向量保存对象

  // ArrayList people = new ArrayList<>()://用ArrayList保存对象.

  people.add (new Person ( "Bob", 20));

  people.add (new Person ( "Zhang", 30));

  people.add (new Person ( "Liu", 18));

  people.add (new Person ( "Kobayashi", 17));

  people.add (new Person ( "Liu", 35));

  Collections.sort (people, new MyComparator ()); // call the method to sort

  Iterator = people.iterator ();

  while (it.hasNext ()) {

  System.out.println (it.Next ());

  }

  }

  }

  class Person {

  String name;

  int age;

  public Person () {

  }

  public Person (String name, int age) {

  this.name = name;

  this.age = age;

  }

  public String toString () {

  return "Name:" + name + ", Age:" + age;

  }

  }

  class MyComparator implements Comparator{// implement Comparator interface, custom comparator, comparison algorithm implemented compare method defined

  public int compare (Person p1, Person p2) {

  int result = p1.age

  // int result = p1.age

  if (result == 0) {

  result = p1.name.compareTo (p2.name);

  }

  return result;

  }

  }

  More about java content and interested readers can view the site topic: "Java object-oriented programming introductory and advanced tutorials", "Java data structures and algorithms tutorial", "Java DOM node operating skills summary", "Java file summary and directory operations skills "and" Java cache operation tips summary "

  In this paper, we hope the java programming help.

  You may also be interested in the article: stream custom grouping and sorting summed implementation java realize six kinds of sorting an array of strings (String array sort) sorted by example Java8 Comparator explain two ways Java sort collection sort of parsing Java entity classes java8 Set in accordance with a field object sorting Java8 Comparator to set: radix sort sorted list of in-depth explanation PHP sorting algorithms (radix Sort) example explanation depth analysis of radix Sort radix sort algorithm thought and C language implementation example c # radix Sort radix sort of Java implementation radix sort radix sort analytic principles and usage

Recommend article

Relate article