如何从java类生成数组
我想从这个如何从java类生成数组,java,arrays,Java,Arrays,我想从这个 GuiClass marek = new GuiClass(1,"Marek"); GuiClass peter = new GuiClass(2,"Peter"); GuiClass tomas = new GuiClass(3,"Tomas"); GuiClass julo = new GuiClass(4,"Julo"); 排列整齐 String [] Gui; Gui = new String[] {"marek","peter","tomas","julo"} 将此数组
GuiClass marek = new GuiClass(1,"Marek");
GuiClass peter = new GuiClass(2,"Peter");
GuiClass tomas = new GuiClass(3,"Tomas");
GuiClass julo = new GuiClass(4,"Julo");
排列整齐
String [] Gui;
Gui = new String[] {"marek","peter","tomas","julo"}
将此数组传递给函数后,可以使用Java 8 Streams API:
String[] Gui = Stream.of(marek, peter, tomas, julo)
.map (GuiClass::getName) // assuming GuiClass has
// getName method
.toArray();
在更一般的情况下,如果您有一个GuiClass数组(即
GuiClass[]
),您可以将该数组传递给Stream.of
。是的,您提到的是可能的。但是以后,如果您计划向数组中添加更多的GuiClass
对象,那么最好在GuiClass
中重写toString()
方法,这样您就不必总是使用变量名(即“marek”、“peter”、“tomas”、“julo”等)作为数组中的值。您可以改为使用以下内容:
new String[] {marek.toString(), peter.toString(), someFutureVariable.toString(),... };
哪个更易于维护。我认为您希望为自己创建的类创建数组 请尝试以下代码作为示例:
public class test {
ClassList cl[] = new ClassList[5];
public test(){
cl[0] = new ClassList("index 1", "name1");
cl[1] = new ClassList("index 2", "name2");
cl[2] = new ClassList("index 3", "name3");
cl[3] = new ClassList("index 4", "name4");
cl[4] = new ClassList("index 5", "name5");
for(int i = 0; i<cl.length; i++){
System.out.println(cl[i].getA()+" "+cl[i].getB());
}
}
public static void main(String args[]){
new test();
}
}
class ClassList{
String a;
String b;
public ClassList(String a,String b){
this.a = a;
this.b = b;
}
public String getA(){ return a; }
public String getB(){ return b; }
}
公共类测试{
类列表cl[]=新类列表[5];
公开考试(){
cl[0]=新类列表(“索引1”、“名称1”);
cl[1]=新类列表(“索引2”、“名称2”);
cl[2]=新类列表(“索引3”、“名称3”);
cl[3]=新类列表(“索引4”、“名称4”);
cl[4]=新类列表(“索引5”、“名称5”);
对于(int i=0;iIt不清楚您拥有什么以及想要实现什么。不太清楚…但是您可以尝试在GuiClass中实现toString()方法,然后:Gui=new String[]{marek.toString(),peter.toString(),tomas.toString(),julo.toString()}假设GuiClass
对第二个参数有一个getter,这是可能的。这对OP可能没有用处。他甚至不知道数组是如何工作的,你正在设计一个复杂的流
类等。IMHO,OP应该先学习基础知识,所以答案应该是如何为
循环编写。@Thomas似乎OP确实发现它很有用。当然,它帮助他完成了代码工作,但他仍然不明白为什么。我正在用eclipse jre7编译…欢迎使用堆栈溢出。请学习如何在您的答案中格式化代码。Thnxs对我来说非常有用。