Hi I have 3 arrays (A,B,C) and A has its own integer 10,and C has its own integer 8 and B has its own integer 5 and how can I sort arrays with its integers and then return those arrays?? it means that you sort integers : 5,8,10 and I want to return their arrays : B,C,A how can I do this? please help me thanks
+1
A:
I have found these integers for those arrays and then I sort those arrays with these integers but I do not know that how can I return their arrays?
You can't return 3 objects from a method. Instead, you could put them in an ArrayList
in the desired order and return it as List
. E.g.:
class MyArrayComparator implements Comparator<int[]> {
public int compare(int[] a1, int[] a2) {
int sn1 = getThatSpecialNumber(a1);
int sn2 = getThatSpecialNumber(a2);
if (sn1 == sn2)
return 0;
else if (sn1 < sn2)
return -1;
else
return 1;
}
}
List orderArrays(int[] a, int[] b, int[] c) {
List<int[]> list = new ArrayList<int[]>();
list.add(a);
list.add(b);
list.add(c);
Collections.sort(list, new MyArrayComparator());
return list;
}
Péter Török
2010-06-21 12:00:08
Does this even compile? Collections.sort returns void, right?
aioobe
2010-06-21 12:26:15
@aioobe, good spot, thanks, fixed :-)
Péter Török
2010-06-21 12:27:38
A:
I'm not sure what do you mean by "has its own integer", but you can store them into i.e. java.util.ArrayList
and then search for the value, i.e.:
ArrayList list = new ArrayList();
....
int number_we_are_searching_for = 12345;
int i = 0;
YourArray a = null;
while(i < list.size())
{
if(list.get(i).SomehowRetrieveThatNumber() == number_we_are_searching_for)
{
a = list.get(i);
break;
}
i++;
}
EDIT: Or add them in desired order (sort them while adding).
cypher
2010-06-21 12:00:15
A:
final int[] a = { 10 }, b = { 5 }, c = { 8 };
// put them in an array. (a List<int[]> works too)
int[][] arrs = { a, b, c };
// sort them using a custom comparator
// (Change "Arrays" to "Collections" if you used a List above)
Arrays.sort(arrs, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return ((Integer) o1[0]).compareTo(o2[0]);
}
});
// Print result and return it:
for (int[] arr : arrs)
System.out.println(Arrays.toString(arr));
return arr;
Output:
[5]
[8]
[10]
aioobe
2010-06-21 12:05:55
`o1[0] - o2[0]` may overflow with large values, giving incorrect result.
Péter Török
2010-06-21 12:17:47