Bishan
Bishan

Reputation: 15720

Why does Collections.max() not return actual max value for a Collection of String?

ArrayList<String> dirNo = new ArrayList<String>();

dirNo.add("1");
dirNo.add("2");
dirNo.add("3");
dirNo.add("4");
dirNo.add("5");
dirNo.add("6");
dirNo.add("7");
dirNo.add("8");
dirNo.add("9");
dirNo.add("10");
dirNo.add("11");

System.out.println("max : " + Integer.parseInt(Collections.max(dirNo)));

After executing above code, print 9 as output.

But actually max value should be 11.

Why am I getting 9 as max ?

Upvotes: 12

Views: 20060

Answers (4)

Anshul Singh Panwar
Anshul Singh Panwar

Reputation: 3

this should work fine

String[] allLongestStrings(String[] inputArray) {
    ArrayList<String> newArray = new ArrayList<String>();
    ArrayList<Integer> arrayIndex = new ArrayList<Integer>();
    ArrayList<String> longestString = new ArrayList<String>();

    for(int i=0; i < inputArray.length;i++){
        newArray.add(inputArray[i]);
        arrayIndex.add(inputArray[i].length());
    }

    int maximumVal = Collections.max(arrayIndex);

    for(int j=0; j < newArray.size();j++){
        if(newArray.get(j).length() >= maximumVal){
            longestString.add(newArray.get(j));
        }    
    }   

    String[] stringArray = longestString.toArray(new 
    String[longestString.size()]);
    return stringArray;

}

Upvotes: 0

Kumar Shashwat
Kumar Shashwat

Reputation: 55

Change String to Integer

ArrayList<Integer> dirNo = new ArrayList<Integer>();

That's it.

Upvotes: 0

Dariusz
Dariusz

Reputation: 22271

You are using a String collection! String comparison is completely different from number comparsion.

String value "2" > "11" because '2' > '1' (first character difference)

Upvotes: 1

NPE
NPE

Reputation: 500733

Since your elements are strings, Collections.max() is returning the value that's the largest lexicographically.

If you wish to compare the strings numerically, you need to use the two-argument version of Collections.max() and supply an appropriate comparator:

    ArrayList<String> dirNo = new ArrayList<String>();

    dirNo.add("1");
    dirNo.add("2");
    dirNo.add("3");
    dirNo.add("4");
    dirNo.add("5");
    dirNo.add("6");
    dirNo.add("7");
    dirNo.add("8");
    dirNo.add("9");
    dirNo.add("10");
    dirNo.add("11");

    Comparator<String> cmp = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    };
    System.out.println("max : " + Collections.max(dirNo, cmp));

Upvotes: 35

Related Questions