在属性ArrayList中创建新对象 [英] create new object in arraylist with attributes
本文介绍了在属性ArrayList中创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的Java和我开始与的ArrayList
工作。我所要做的就是创建一个的ArrayList
为学生。每个学生都有与之相关联的不同的属性(姓名,身份证
)。我试图找出如何添加一个新的学生对象与此属性。以下是我有:
的ArrayList<学生> studentArray;
公益助学(字符串名称,诠释的id){
this.fname =名称;
this.stId = ID;
}
公共Stromg的getName(){
返回FNAME;
}
公众诠释的getId(){
返回STID;
}
公共布尔setname可以(字符串名称){
this.fname =名称;
返回true;
}
公共布尔setIdNum(INT ID){
this.stId = ID;
返回true;
}
解决方案
您需要的是类似以下内容:
进口的java.util。*;类TestStudent
{
公共静态无效的主要(字符串ARGS [])
{
清单<的Student GT; StudentList =新的ArrayList<的Student GT;();
学生tempStudent =新学生();
tempStudent.setName(雷伊);
tempStudent.setIdNum(619);
StudentList.add(tempStudent);
的System.out.println(StudentList.get(0).getName()+,+ StudentList.get(0).getId());
}
}类学生
{
私人字符串FNAME;
私人诠释STID; 公共字符串的getName()
{
返回this.fname;
} 公众诠释的getId()
{
返回this.stId;
} 公共布尔setname可以(字符串名称)
{
this.fname =名称;
返回true;
} 公共布尔setIdNum(INT ID)
{
this.stId = ID;
返回true;
}
}
I am new to Java and I am starting to work with ArrayLists
. What I am trying to do is create an ArrayList
for students. Each student has different attribute associated with them (name, id
). I am trying to figure out how to add a new student object with this attributes. Here is what I have:
ArrayList < Student > studentArray;
public Student(String name, int id) {
this.fname = name;
this.stId = id;
}
public Stromg getName() {
return fname;
}
public int getId() {
return stId;
}
public boolean setName(String name) {
this.fname = name;
return true;
}
public boolean setIdNum(int id) {
this.stId = id;
return true;
}
解决方案
What you need is something like the following:
import java.util.*;
class TestStudent
{
public static void main(String args[])
{
List<Student> StudentList= new ArrayList<Student>();
Student tempStudent = new Student();
tempStudent.setName("Rey");
tempStudent.setIdNum(619);
StudentList.add(tempStudent);
System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
}
}
class Student
{
private String fname;
private int stId;
public String getName()
{
return this.fname;
}
public int getId()
{
return this.stId;
}
public boolean setName(String name)
{
this.fname = name;
return true;
}
public boolean setIdNum(int id)
{
this.stId = id;
return true;
}
}
这篇关于在属性ArrayList中创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文