Today I was practising java programing and come across a program making me wonder that what will happen if I find maximum and minimum of a String in an Array.
今天,我正在练习java编程,并遇到了一个程序,让我想知道如果我在数组中找到一个字符串的最大值和最小值会发生什么。
// Creating an Array List
ArrayList<String> myArrayList = new ArrayList<String>();
// Adding values
myArrayList.add("Hello World");
myArrayList.add("My Name is Some Body");
myArrayList.add("I am many Years old");
myArrayList.add("And I love Java programming");
// To find min and max in Array
String min = Collections.min(myArrayList);
String max = Collections.max(myArrayList);
// Print min and max in Array
System.out.println("Min: " +min);
System.out.println("Max: " +max);
It gives an output of:
输出为:
Min: And I love Java programming
Max: My Name is Some Body
I was curious that on what bases it determines the maximum and minimum of a String array? And how can it be useful in a program?
我很好奇它在什么基础上决定了字符串数组的最大值和最小值?它如何在程序中有用呢?
3 个解决方案
#1
2
The Collections.max
and Collections.min
compare objects in their natural order.
的集合。马克斯和集合。最小按物体的自然顺序进行比较。
For String
s, it's lexicographic (i.e. alphabetic) comparison.
对于字符串,它是字典(即字母)比较。
Amongst the many uses of natural order comparison is the fact you can easily sort String
alphabetically.
在自然顺序比较的众多用途中,你可以很容易地按字母顺序排序。
#2
1
It's doing String comparison in this case. Check the min method in collections class.
这里是字符串比较。检查集合类中的最小方法。
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) < 0)
candidate = next;
}
return candidate;
}
#3
1
It checks each word first letter ASCII code. If the ASCII code of that first letter is small then others then it will consider as small string other wise it will consider it is larger then others.
它检查每个单词的第一个字母ASCII码。如果第一个字母的ASCII码是小的,那么它将被认为是小的字符串,其他方面它会认为它比其他的要大。
#1
2
The Collections.max
and Collections.min
compare objects in their natural order.
的集合。马克斯和集合。最小按物体的自然顺序进行比较。
For String
s, it's lexicographic (i.e. alphabetic) comparison.
对于字符串,它是字典(即字母)比较。
Amongst the many uses of natural order comparison is the fact you can easily sort String
alphabetically.
在自然顺序比较的众多用途中,你可以很容易地按字母顺序排序。
#2
1
It's doing String comparison in this case. Check the min method in collections class.
这里是字符串比较。检查集合类中的最小方法。
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) < 0)
candidate = next;
}
return candidate;
}
#3
1
It checks each word first letter ASCII code. If the ASCII code of that first letter is small then others then it will consider as small string other wise it will consider it is larger then others.
它检查每个单词的第一个字母ASCII码。如果第一个字母的ASCII码是小的,那么它将被认为是小的字符串,其他方面它会认为它比其他的要大。