如何将内容分组并将其作为一个对象添加到ArrayList?

时间:2016-08-31 09:00:52

标签: java

我有一个学生列表,其中包含以下详细信息:姓名,标识,主题,所以现在我想使用一个对象存储名称,标识和主题的数据结构

例如

Name: Snow 
Id=1 
Subject=CS and 
 Name: John
Id=2 
Subject =IT

我该怎么做?

2 个答案:

答案 0 :(得分:0)

创建该Student类的List并在列表中添加对象。但您必须通过构造函数或setter方法初始化类属性,下面的示例仅向您展示对象如何存储在List中。

List <Student> studentList = new ArrayList<Student>();
Student s1= new Student();
studentList.add(s1);

答案 1 :(得分:0)

为HashMap类创建一个对象,并使用put()方法传递所有id和主题名称,因为它采用id和name的组合,然后将其转换为Set类的对象,最后使用addAll( )ArrayList的方法将set对象传递给addAll()方法完成它,我们还没有传递hashmap对象,因为hashmap类确实包含allAll()方法,下面是希望它帮助你的代码

import java.util.*;
public class GroupA{
public static void main(String...s){
ArrayList al=new ArrayList();
HashMap<Integer,String>hs=new HashMap<>();

hs.put(100&#34; AAA&#34);

hs.put(101,"bbb");

hs.put(102&#34; CCC&#34);

Set sp=hs.entrySet();
al.addAll(sp);
System.out.println(al);
}
}