hi,
i want to sort this
"192.168.1.12"
"192.168.1.11"
"192.168.1.13"
please give me sample code or some tips.
Printable View
hi,
i want to sort this
"192.168.1.12"
"192.168.1.11"
"192.168.1.13"
please give me sample code or some tips.
Look in the API doc for the sort method. The Index link at the top of the API doc page then select S. Then read the doc for those classes. When you find one that looks useful, use Search to find code samples.
As a simple hint, those all things are strings. Search on the web about how to sort strings. As Norm says, please read Java doc before ask a code and try something to implement by yourself.
What you show are Strings that have the dots in the same columns.
What if the sub parts of the address are different lengths?
Then you'll need to convert the 4 parts of the address to another format(say byte) and concatenate them to a long, sort the longs and then extract the 4 bytes back to decimal digits.
No need to worry about that.
Code:String[] arr = new String[]{"192.168.2.12", "192.168.1.1", "192.168.1.14"};
java.util.Arrays.sort(arr);
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
That sorts in character sequence. What about dotted IP address sequence? Will sorts of the two types of data give the same results?
I'm not clear what you mean by IP address sequence Norm.
In the sense of int, they are just 32 bits ints. You might sort them unsigned. If they have in int, easily can compare them, as I don in the last post using Array.sort()
If you have them as InetAddress's, call GetAddress() and stuff the
byte[4] into an int. Then do the same thing as above.
Working with strings is the most easiest way I think.
Take the case of these two addresses. Which should be first:
4.22.22.22
22.22.22.22
I'd say they are in ascending order.
A String sort would change their order
Yes that make sense. Such like your values cannot work fine with strings. So you can use one of other two ways I have explain in the above post. What you have to make sure to working on with strings is, each address segment should be in three digits. Actually same number of digits are ok.