import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* Задача по алгоритмам Написать программу, которая: 1. вводит с консоли число N > 0 2. потом вводит N чисел с консоли 3. выводит на экран максимальное из введенных N чисел. */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String raz = reader.readLine(); int razi = Integer.parseInt(raz); List myList = new ArrayList(); for(int i=0; i<razi;i++){ String x = reader.readLine(); int y = Integer.parseInt(x); myList.add(y); } int maxi = Collections.max(myList); System.out.println(Collections.max(myList)); } } 

If you remove the line int maxi = Collections.max(myList); then the code runs without problems. But I was interested, why I can not assign the maximum value from the list variable maxi ? IDE shows an error.

  • And what a mistake? - VladD
  • Error: (30, 36) java: incompatible types: java.lang.Object cannot be converted to int - Araz Hajiyev

2 answers 2

An error message explains what's wrong.

Since you are using an untyped List , the declared type of objects in it is Object . Therefore, the declared maximum type is also Object . And the fact that there will actually be a number does not matter. Could you put a string or any other object in it, how can the compiler control it?

You must declare that your list will contain only numbers:

 List<Integer> myList = new ArrayList<Integer>(); 

Then when you try to insert there is not a number, the compiler will swear at you.

  • It is possible and so, yes) - LEQADA

Because Collections.max(myList) returns an object and you immediately try to assign an int . Do this:

 int maxi = (Integer) Collections.max(myList); 
  • Is not the returned object a number? After all, the function is mathematical, and if the list would be one string, then this method would not work (would give an error). - Araz Hajiyev
  • @ArazHajiyev, why? This would work with strings. - LEQADA
  • and what would be the result? )))) the maximum that it would give? )) - Araz Hajiyev
  • @ArazHajiyev, would return the maximum element in lexicographical order. For example, if you entered "a, b, c", you would issue "c". - LEQADA
  • 2
    @ArazHajiyev: Collections.max tries to compare elements with each other. If it can compare (for example, they are all numbers or strings), the maximum is returned. If it cannot (for example, there are numbers and strings), a run-time error will occur. Here is an example: ideone.com/MycFsz - VladD