I am getting the following error.
import java.util.*;
import java.io.*;
public class ShufflingListAndArray
{
public static void main(String[] args) throws IOException
{
开发者_如何学Python 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
Change List services ...
to List<String> services
List.get() returns an Object. You need to cast it or use generics to store it in a String variable.
To use generics:
List<String> services = ...
To cast it:
String s = (String)services.get(rnd.nextInt(services.size()));
The compilation error is pretty clear:
found : java.lang.Object
required: java.lang.String
It says that Object
is returned (found), but that your code requires it to be a String
.
You need to either parameterize the List
with help of Generics, so that it will instantly return a String
on every List#get()
call (more recommended):
List<String> services = Arrays.asList("COMPUTER", "DATA", "PRINTER");
or to downcast the returned Object
to String
yourself:
String s = (String) services.get(rnd.nextInt(services.size()));
need to specify it is a list of strings
List<String> services = Arrays.asList(new String[] {"COMPUTER", "DATA", "PRINTER"});
From your this question, it seems to me that you are using 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);
}
}
精彩评论