如何按升序排序?我有对象[]

时间:2014-12-11 06:43:27

标签: java arrays sorting

如何将Object[]转换为数组并按升序对其进行排序?需要创建Array个对象然后我们可以使用Arrays.sort();请建议按升序排序

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import sun.security.util.Length;

public class JavaInterview{

        public static void main(String a[]){
            int[] arr1 = {4,7,3,9,2};
            int[] arr2 = {3,2,12,9,40,32,4};
          Set hashSet= new HashSet<Integer>();

                for(int i= 0; i<arr1.length; i++) hashSet.add(arr1[i]);
                for (int i=0 ; i<arr2.length; i++) hashSet.add(arr2[i]);
          //Converting into Array   
            Object[] obj=   hashSet.toArray();
            for (int i=0; i<obj.length; i++)
            {
                System.out.println(obj[i]);

            }

        }                  

}

2 个答案:

答案 0 :(得分:1)

使用TreeSet,该系列将为您排序。通用类型在左侧。像,

int[] arr1 = { 4, 7, 3, 9, 2 };
int[] arr2 = { 3, 2, 12, 9, 40, 32, 4 };
Set<Integer> treeSet = new TreeSet<>();

for (int i = 0; i < arr1.length; i++)
    treeSet.add(arr1[i]);
for (int i = 0; i < arr2.length; i++)
    treeSet.add(arr2[i]);
Integer[] arr = treeSet.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));

输出

[2, 3, 4, 7, 9, 12, 32, 40]

如果您可以使用对象包装器类型,则可以使用addAllArrays.asList(T...)来消除循环

Integer[] arr1 = { 4, 7, 3, 9, 2 };
Integer[] arr2 = { 3, 2, 12, 9, 40, 32, 4 };
Set<Integer> treeSet = new TreeSet<>();
treeSet.addAll(Arrays.asList(arr1));
treeSet.addAll(Arrays.asList(arr2));
Integer[] arr = treeSet.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));

与之前相同的输出。

答案 1 :(得分:0)

import java.util.Arrays;
import java.util.Collections;
import java.util.*;
import java.util.Set;


public class Sorting{

        public static void main(String a[]){
            int[] arr1 = {4,7,3,9,2};
            int[] arr2 = {3,2,12,9,40,32,4};
        //first sort your array
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        //then use LinkedHashSet to store because it maintains order
          Set hashSet= new LinkedHashSet<Integer>();

                for(int i= 0; i<arr1.length; i++) hashSet.add(arr1[i]);
                for (int i=0 ; i<arr2.length; i++) hashSet.add(arr2[i]);
          //Converting into Array   
            Object[] obj=   hashSet.toArray();
            for (int i=0; i<obj.length; i++)
            {
                System.out.println(obj[i]);

            }

        }                  

}

对你有帮助吗?