使用随机数在java中列出

时间:2010-03-02 01:32:15

标签: java

我收到以下错误。

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);
  }
} 

编译完上面的代码后,我收到以下错误。

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

5 个答案:

答案 0 :(得分:5)

List services ...更改为List<String> services

答案 1 :(得分:1)

List.get()返回一个Object。您需要将其强制转换或使用泛型将其存储在String变量中。

使用泛型:

List<String> services = ...

投下它:

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

答案 2 :(得分:1)

编译错误很清楚:

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

它表示Object已返回(找到),但您的代码要求它为String

您需要在Generics的帮助下参数化List,以便在每次String来电时立即返回List#get()(建议更多):

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

downcast自己返回ObjectString

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

答案 3 :(得分:0)

需要指定它是一个字符串列表

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

答案 4 :(得分:0)

从您的this问题来看,在我看来,您使用的是旧版Java而不是Java 5.

以下代码可以使用它:

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);
  }
}