Java的比较和排序

1- Java基本类型和引用类型
2- 什么是栈和堆?
3- 存储在内存中的原始类型
4- 存储在内存中的引用类型
5- Java中的类型比较
6- 原始类型的比较
7- 引用类型的比较
7.1- 使用==操作符来比较引用类型
7.2- 使用equals(..) 来比较引用类型
7.3- 重写equals(Object)方法
8- 排序字符串数组的例子
9- 对象可以相互比较(可比)
10- 排序List
11- 使用Comparator排序

1- Java基本类型和引用类型

首先,我们需要区分Java中的基本类型和引用类型。
在Java中,我们有8种基本类型。
  • 基本类型
类型 Bit/Bytes 值范围
boolean 1 bit True 或 False
char 16 bit/ 2 bytes 0 - 65535
byte 8 bit/ 1 byte -128 - 127
short 16 bit/ 2 bytes -32768 - 32767
int 32 bits/ 4 bytes -2147483648 - 2147483647
long 64 bits/ 8 bytes -9,223,372,036,854,775,808 至 -9,223,372,036,854,775,808
(-2^63 至 -2^63)
float 32 bits/ 4 bytes -3.4028235 x 10^38 至 3.4028235 x 10^38
double 64 bits/ 8 bytes -1.7976931348623157 x 10^308 至 1.7976931348623157 x 10^308
所有其它类型从Object扩展,所以它们是引用类型。

2- 什么是栈和堆?

变量存储在栈或堆,那么什么是栈和堆?

3- 内存中的原始类型存储在哪里

首先,Java没有真正使任何保证变量对应于的存储单元; 例如,你的方法中可能以这样的方式来优化 - “i”被存储在一个寄存器 —或者如果编译器可以找到从来没有真正使用它的值就可能不会存储,或者,如果它能够通过代码跟踪并直接使用适当的值。看到一个代码片段:
// Create  variable a, and assign a value of 100.
int a = 100;

// Assign new value to a
a = 200;

// Create variable b, assigned equal to a
int b = a;
Java采取以下措施:
Java的比较和排序_第1张图片

4- 存储在内存中的引用类型

当您使用新的(例如:new Object ()),Java将在存储创建新实体。声明一个变量,并通过new操作符初始化它的值,如 Object a = new Object (); Java将在存储器中创建一个新的实体,及一个参考指针指迥新创建的实体的存储位置。
当你声明一个变量b Object b = a; 不会有实体在内存中创建,Java只创建一个参考b, 指针指向同一位置。
// Declare and initialize the object.
Object a =  new Object();

// reinitialize object
a = new String("Text");

// Declare object 'b' and assign it to the object 'a'.
Object b =  a;

Java的比较和排序_第2张图片
5- Java的类型比较

Java有两种比较类型:
  • 使用操作符 ==
  • 使用equals方法 (..)
用==操作符来比较原始和引用类型。
运算符 equals() 是仅用于引用类型的方法。

6- 原始类型的比较

借助基本类型,我们只有一个办法通过 == 操作符来比较
// Create  variable a, assign a value of 200
// A memory area (1) is created that contains the value of 200.
int a = 200;

// Create a variable b, assign a value of 200.
// A memory area (2) is created that contains the value of 200.
int b = 200;

// The primitive compared with each other by value
// return true.
boolean c = (a == b);

7- 引用类型的比较

7.1- 使用==操作符来比较引用类型

当使用==操作符比较两个对象引用, 这意味着在比较2个对象引用指向的位置。本质上,它是检查2个对象引用是否指向内存的实体还是不一样。
举个例子:
  • ReferenceEeDemo.java
package com.yiibai.tutorial.comparation;

public class ReferenceEeDemo {

    public static void main(String[] args) {

         // NOTE: For String, two ways to initialize the object below are not the same:
        String str1 = "String 1";
        String str2 = new String("String 1");

        // The new operator create the memory (1)
        // Contains the  "This is text"  String
        // And s1 is a reference that points to (1)
        String s1 = new String("This is text");

        // The new operator create the memory (2)
        // Contains the  "This is text" String
        // And s2 is a reference that points to (2)
        String s2 = new String("This is text");

       
        // Use the operator==  to compare s1 and s2.
        // Results in false.
        // It is obviously different from what you think.
        // The reason is the type of reference
        // Operator  == compares the positions that they point to.
        boolean e1 = (s1 == s2); // false

        System.out.println("s1 == s2 ? " + e1);

      
        // Without any new operator.
        // Java  creates a reference  named 'obj'
        // And pointing to a memory area that s1 points to.
        Object obj = s1;

   
        // 2 references 'obj' and 's1' are all pointing to one area of memory.
        // Results is true
        boolean e2 = (obj == s1); // true

        System.out.println("obj == s1 ? " + e2);
    }
}
执行结果如下:
Java的比较和排序_第3张图片

7.2- 使用equals(..)来比较引用类型

  • StringComparationDemo.java
package com.yiibai.tutorial.comparation;

public class StringComparationDemo {

    public static void main(String[] args) {

        String s1 = new String("This is text");

        String s2 = new String("This is text");

        // s1 and s2 Comparison, use equals(..)
        boolean e1 = s1.equals(s2);

        // true
        System.out.println("first comparation: s1 equals s2 ? " + e1);

        
        s2 = new String("New s2 text");

        boolean e2 = s1.equals(s2);

        // false
        System.out.println("second comparation: s1 equals s2 ? " + e2);
    }
    

}
运行例如:
first comparation: s1 equals s2 ? true
second comparation: s1 equals s2 ? false

7.3- 重写equals(Object)方法

equals(Object)方法是Object类的一个可行的方法,所有的子类继承此方法。 在某些情况下,您可以在子类中覆盖此方法。
  • NumberOfMedals.java
package com.yiibai.tutorial.comparation.equals;

public class NumberOfMedals {


    // Number of gold medals
    private int goldCount;

    // Number of silver medals
    private int silverCount;

    // Number of bronze medals
    private int bronzeCount;

    public NumberOfMedals(int goldCount, int silverCount, int bronzeCount) {
        this.goldCount = goldCount;
        this.silverCount = silverCount;
        this.bronzeCount = bronzeCount;
    }

    public int getGoldCount() {
        return goldCount;
    }

    public int getSilverCount() {
        return silverCount;
    }

    public int getBronzeCount() {
        return bronzeCount;
    }


    // Override the equals(Object) method of class Object.
    @Override
    public boolean equals(Object other) {

        // if other is null, return false.
        if (other == null) {
            return false;
        }

        
        // If the 'other' is not a NumberOfMedals
        // return false
        if (!(other instanceof NumberOfMedals)) {
            return false;
        }

        NumberOfMedals otherNoM = (NumberOfMedals) other;
        
        if (this.goldCount == otherNoM.goldCount
                && this.silverCount == otherNoM.silverCount
                && this.bronzeCount == otherNoM.bronzeCount) {
            return true;
        }
        return false;
    }
    
}
  • NumberOfMedalsComparationDemo.java
package com.yiibai.tutorial.comparation.equals;

public class NumberOfMedalsComparationDemo {

    public static void main(String[] args) {

        NumberOfMedals american = new NumberOfMedals(40, 15, 15);

        NumberOfMedals japan = new NumberOfMedals(10, 5, 20);

        NumberOfMedals korea = new NumberOfMedals(10, 5, 20);

        System.out.println("Medals of American equals Japan ? "
                + american.equals(japan));

        System.out.println("Medals of Korea equals Japan ? "
                + korea.equals(japan));
    }

}
运行实例:
Medals of American equals Japan ? false
Medals of Korea equals Japan ? true

8- 排序一个字符串数组例子

字符串类的对象可以彼此按字母的规则进行比较。下面的例子演示了如何在Java中使用可用的实用工具方法来排列一个String数组。
  • StringArraySortingDemo.java
package com.yiibai.tutorial.sorting;

import java.util.Arrays;

public class StringArraySortingDemo {

    public static void main(String[] args) {
        String[] fruits = new String[] { "Pineapple", "Apple", "Orange",
                "Banana" };

        // Use a static method of class Arrays to sort.
        // Arrays.sort (Object [])
        Arrays.sort(fruits);

        for (int i = 0; i < fruits.length; i++) {
            System.out.println("fruits " + i + " : " + fruits[i]);
        }
    }
    
}
运行实例:
fruits 0 : Apple
fruits 1 : Banana
fruits 2 : Orange
fruits 3 : Pineapple

9- 对象可以相互比较(可比)

// You write a class which simulates an actor (Actor).
// You want to arrange the order of actors according to the principle of last name prior then to first name.
// At this point, it arises  situations requiring to  compare Actor objects. 

public class Actor {
  
    private String firstName;
 
    private String lastName;
}
  • Actor.java
package com.yiibai.tutorial.sorting;


// To be compared with each other, Actor classes
// must implement Comparable interface
public class Actor implements Comparable {

    private String firstName;
    private String lastName;

    public Actor(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

   
    // Compare this Actor with another Actor.
    // According to  comparison principle of lastName first,
    // then compare firstName.
    @Override
    public int compareTo(Actor other) {
    
        // String can be compared with each other
        // (String implement Comparable  interface)
        // Compare lastName between two objects.
        int value = this.lastName.compareTo(other.lastName);
   
        // If lastName of two objects are not equal.
        if (value != 0) {
            return value;
        }   
        
        // In case  lastName of 2 object are same.
        // Next, compare firstName.
        value = this.firstName.compareTo(other.firstName);
        return value;
    }

}
  • ActorSortingDemo.java
package com.yiibai.tutorial.sorting;

public class ActorSortingDemo {

    public static void main(String[] args) {

        Actor actor1 = new Actor("Mischa", "Barton");
        Actor actor2 = new Actor("Christian", "Bale");
        Actor actor3 = new Actor("Joan", "Collins");
        Actor actor4 = new Actor("Gemma", "Arterton");
        Actor actor5 = new Actor("Daniel", "Craig");

        Actor[] actors = new Actor[] { actor1, actor2, actor3, actor4, actor5 };

       
        // We use an algorithm to rearrange the array above.
        // Sort the Actor objects in  gradually increase order.
        for (int i = 0; i < actors.length; i++) {

            for (int j = i + 1; j < actors.length; j++) {
               
                // If later Actor is smaller than  prior Actor
                // Make the swap positions with each other.
                if (actors[j].compareTo(actors[i]) < 0) {

                    // Use a temporary variable.
                    Actor temp = actors[j];
                    actors[j] = actors[i];
                    actors[i] = temp;
                }
            }
        }

        // Print out
        for (int i = 0; i < actors.length; i++) {
            System.out.println(actors[i].getFirstName() + "  "
                    + actors[i].getLastName());
        }

    }
    
}
运行实例:
Gemma  Arterton
Christian  Bale
Mischa  Barton
Joan  Collins
Daniel  Craig
使用Arrays.sort(Object [])排序上面例子的列表:
  • ActorSortingDemo2.java
package com.yiibai.tutorial.sorting;

import java.util.Arrays;

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

        Actor actor1 = new Actor("Mischa", "Barton");
        Actor actor2 = new Actor("Christian", "Bale");
        Actor actor3 = new Actor("Joan", "Collins");
        Actor actor4 = new Actor("Gemma", "Arterton");
        Actor actor5 = new Actor("Daniel", "Craig");

        Actor[] actors = new Actor[] { actor1, actor2, actor3, actor4, actor5 };
   
  
        // Use Arrays.sort(Object []) to arrange.
        Arrays.sort(actors);  
        

        // Print out
        for (int i = 0; i < actors.length; i++) {
            System.out.println(actors[i].getFirstName() + "  "
                    + actors[i].getLastName());
        }

    }
}

10- List排序

可以参考在本教程Java集合框架:
  • http://www.yiibai.com/java/java-collection-framework-tutorial.html
实例:
  • ListSortingDemo.java
package com.yiibai.tutorial.sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSortingDemo {

    public static void main(String[] args) {

        Actor actor1 = new Actor("Mischa", "Barton");
        Actor actor2 = new Actor("Christian", "Bale");
        Actor actor3 = new Actor("Joan", "Collins");
        Actor actor4 = new Actor("Gemma", "Arterton");
        Actor actor5 = new Actor("Daniel", "Craig");

        // A list containing the elements can be compared with each other.
        List actors = new ArrayList();

        actors.add(actor1);
        actors.add(actor2);
        actors.add(actor3);
        actors.add(actor4);
        actors.add(actor5);

        // Use Collections.sort(List)
        // to sort a list.
        Collections.sort(actors);

        for (Actor actor : actors) {
            System.out.println(actor.getFirstName() + "  "
                    + actor.getLastName());
        }

    }
    
}

11- 排序使用比较

在上面的例子中,我们进行排序数组或列表,其中的元素能够相互比较(因为它实现Comparable接口)。与没有实现Comparable接口的类的问题是,是否可以排列。在这种情况下,应该提供一个比较器(Comparator)。这是排序对象的规则。
  • Person.java
package com.yiibai.tutorial.comparator;

public class Person {

   private int age;
   private String fullName;

   public Person(String fullName, int age) {
       this.fullName = fullName;
       this.age = age;
   }

   public int getAge() {
       return age;
   }

   public String getFullName() {
       return fullName;
   }
}
  • PersonComparator.java
package com.yiibai.tutorial.comparator;

import java.util.Comparator;

 
//This class implements the  Comparator  interface
//It can be considered as the rule to compare the Person objects.
public class PersonComparator implements Comparator {

 
    
    // Override  compare methods.
    // Specify the  comparison rules between 2 Person objects.
    @Override
    public int compare(Person o1, Person o2) {
 
        // Two null objects, regarded as equal.
        if (o1 == null && o2 == null) {
            return 0;
        }
 
        // If o1 null, regarded as o2 is  larger
        if (o1 == null) {
            return -1;
        }
 
        // If o2 null,  regarded as o1 is  larger .
        if (o2 == null) {
            return 1;
        }
 
        
        // Rule:
        // Sort gradually increase over age.
        int value = o1.getAge() - o2.getAge();
        if (value != 0) {
            return value;
        }
       
        // Case where the objects are the same age, compare to FULLNAME
        // Compare by Alphabet.
        value = o1.getFullName().compareTo(o2.getFullName());
        return value;
    }

}
  • ComparatorSortingDemo.java
package com.yiibai.tutorial.comparator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ComparatorSortingDemo {

    public static void main(String[] args) {
        Person person1 = new Person("Marry", 20);
        Person person2 = new Person("Tom", 21);
        Person person3 = new Person("Daniel", 21);
        Person person4 = new Person("Mischa", 18);
        Person person5 = new Person("Christian", 20);

         // An array is not sorted
        Person[] array = new Person[] { person1, person2, person3, person4,
                person5 };

       
        // Sort the array, use:  Arrays.sort(T[],Comparator)
        // Provide a Comparator.
        Arrays.sort(array, new PersonComparator());

        for (Person person : array) {
            System.out.println("Person: " + person.getAge() + " / "
                    + person.getFullName());
        }
        
        System.out.println("------------------------");
        
        // For List
        List list = new ArrayList();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        list.add(person4);
        list.add(person5);

    
        // Sort the array, use:  Arrays.sort(T[],Comparator)
        // Provide a Comparator.
        Collections.sort(list, new PersonComparator());

        for (Person person : list) {
            System.out.println("Person: " + person.getAge() + " / "
                    + person.getFullName());
        }
    }
    
}
运行实例,结果如下:
Person: 18 / Mischa
Person: 20 / Christian
Person: 20 / Marry
Person: 21 / Daniel
Person: 21 / Tom
------------------------
Person: 18 / Mischa
Person: 20 / Christian
Person: 20 / Marry
Person: 21 / Daniel
Person: 21 / Tom

你可能感兴趣的:(java基础,java)