我想知道是否有办法做到这一点:
String **type** = "Player"
ArrayList<**type**> players = new ArrayList();
我的意思是用变量字符串定义对象类型。我输入“玩家”,它可以是 Player
在这里,但是可以引入变量类型的方法怎么样?像这样的事情:
public static void main (String[] args)
{
system.out.println("Select a type that u wanna make an array of");
system.out.println("1. Player");
system.out.println("2. Team");
Scanner in = new Scaner (System.in);
createArray(in.next());
}
public static void createArray(String **type**)
{
ArrayList<**type**> x = new ArrayList();
}
这可能吗?
最佳答案
逃离Stringly-typed思考并简单地创建您自己的类来捕获您想要的有关玩家的所有信息。
public class Player {
// fields, methods to describe a player
}
public class Team {
// fields, methods to describe a team
}
那么,你的ArrayList
会像你期望的那样工作。
List<Player> players = new ArrayList<>();
List<Team> teams = new ArrayList<>();
附带说明:您当前的代码结构只会在该方法中创建列表,之后将不可用。如果你想要回来,你必须返回 ArrayList<Player>
,或者在 main
内声明它当你去使用它时。
关于java - 引入String来定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674186/