在Java中,您不能动态声明变量名称。 Java变量名声明编译时不是运行时。
但从我能理解你的问题你可以使用Map来实现这一点。使用Map您可以使用您定义的关键字来存储对象。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Student {
PrintStream p=new PrintStream(System.out);
Scanner sc = new Scanner(System.in);
String reg;
Student(){
//p.println("Enter the name of the student:");
}
public void nstd() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList cse=new ArrayList();
ArrayList ece=new ArrayList();
ArrayList mec=new ArrayList();
ArrayList eee=new ArrayList();
HashMap cseStudents= new HashMap<>();
p.println("Enter the name of the student:");
String name=br.readLine();
p.println("Choose one group from fallowing:");
String group=br.readLine();
if(group.matches("^[Cc][Ss][Ee]$")){
cse.add(name);
cseStudents.put(name,new Acad());
}
if(group.matches("^[Ee][Cc][Ee]$")){
ece.add(name);
}
if(group.matches("^[Mm][Ee][Cc]$")){
mec.add(name);
}
if(group.matches("^[Ee]{3}$")){
eee.add(name);
}
}
}
您可以访问使用
Acad required=cseStudents.get(name);
有几种类型的Map实现这可能是你[HashMap中] [1],LinkedHashMap的,TreeMap和哈希表有用所需的对象随时随地。
每个人都有自己的优势。基本上,
HashMap中
此类不保证作为对地图的顺序;在 特别是,它不能保证该订单随着时间的推移将保持恒定 。该实现为基本操作(获取和放置)提供了 的恒定时间性能。
LinkedHashMap的
该链表维护,其中键插入到地图(插入顺序)的顺序。
TreeMap中
该地图是根据其键的自然顺序进行排序,或者通过比较在地图创建时提供,这取决于所使用的构造方法。
哈希表
几乎类似于HashMap中除了这是同步的。