Sort an oversized string array in java -
i trying sort oversized string array of emails. when don't fill oversized array beforehand, nullpointerexception. when fill array empty strings, code sorts list of emails alphabetically, puts sorted list of emails behind empty strings. how sort list of emails first lists emails alphabetically in array , lists empty strings?
example: if entered example1@domain, example2@domain, star, , apple, following quote output. want of empty strings behind entered data, not before it.
[, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , apple, example1@domain, example2@domain, star]
code:
string[] data = new string[array_size]; public static string[] addemail(string[] data, string email, int index) { int size = data.length; data[index] = email; int i,j; string temp; system.out.println(arrays.tostring(data)); (j = 1; j < data.length; j++) { temp = data[j]; = j - 1; while (i >= 0) { if (temp.compareto(data[i]) > 0) { break; } data[i + 1] = data[i]; i--; } data[i + 1] = temp; system.out.println(arrays.tostring(data)); } system.out.println(arrays.tostring(data)); return data; }
edit: have code own sort logic "efficiency" in project. have use oversized array.
don't use oversized array. use collection
. since want sorted suggest sortedset
. might write like
public static sortedset<string> addemail(sortedset<string> coll, string email) { if (coll == null) { coll = new treeset<>(); } coll.add(email); return coll; }
if wanted use string[]
adapt above algorithm like
public static string[] addemail(string[] arr, string email) { sortedset<string> coll = new treeset<>(); if (arr != null) { coll.addall(arrays.aslist(arr)); } coll.add(email); return coll.toarray(new string[coll.size()]); }