List in java using random numbers

I get the following error.

import java.util.*;
import java.io.*;

public class ShufflingListAndArray
{
  public static void main(String[] args) throws IOException

{
    List services = 


    //Arrays.asList("COMPUTER", "DATA", "PRINTER");

 Arrays.asList(new String[] {"COMPUTER", "DATA", "PRINTER"}); 

   Random rnd=new Random();
  String s = services.get(rnd.nextInt(services.size()));

    Collections.shuffle(services);


    //Collections.sort(list);


    System.out.println("List sorting :"+ services);
  }
} 

After compiling the above code, I get the following error.

C:\>javac ShufflingListAndArray.java
ShufflingListAndArray.java:17: incompatible types
found   : java.lang.Object
required: java.lang.String
  String s = services.get(rnd.nextInt(services.size()));
                         ^
1 error
+3
source share
5 answers

Change List services ...toList<String> services

+5
source

List.get () returns an object. You need to drop it or use generics to store it in a String variable.

Using generics:

List<String> services = ...

To do this:

String s = (String)services.get(rnd.nextInt(services.size()));
+1
source

:

found   : java.lang.Object
required: java.lang.String

, Object (), , String.

List Generics, String on List#get() ():

List<String> services = Arrays.asList("COMPUTER", "DATA", "PRINTER");

or , to downcast return Objectto Stringyourself:

String s = (String) services.get(rnd.nextInt(services.size()));
+1
source

need to indicate that this is a list of strings

List<String> services = Arrays.asList(new String[] {"COMPUTER", "DATA", "PRINTER"}); 
0
source

From your this question, it seems to me that you are using an older version of Java than Java 5.

The following code should work with it:

import java.util.*;
import java.io.*;

public class ShufflingListAndArray {
  public static void main(String[] args) throws IOException {
    List services = Arrays.asList(new String[] {"COMPUTER", "DATA", "PRINTER"}); 
    Random rnd = new Random();
    String s = (String) services.get(rnd.nextInt(services.size()));
    Collections.shuffle(services);
    System.out.println("List sorting :" + services);
  }
} 
0
source

Source: https://habr.com/ru/post/1734979/


All Articles