怎么创建list集合,如何创建list集合
java中的list集合怎么用
ListString list = new ArrayListString();//创建集合对象;
list.Add("1");//在集合里存入数据
list.Add("2");
List是一个接口,不能实例化,创建对象时要使用他的实现类ArrayList(其他);
看看
java对象,如何将一个list集合
代码如下:
import?java.io.File;
import?java.io.FileWriter;
import?java.io.IOException;
import?java.util.ArrayList;
import?java.util.List;
class?Music?{
private?int?id;
private?String?name;
private?String?singer;
public?Music(int?id,?String?name,?String?singer)?{
this.id?=?id;
this.name?=?name;
this.singer?=?singer;
}
public?int?getId()?{
return?id;
}
public?void?setId(int?id)?{
this.id?=?id;
}
public?String?getName()?{
return?name;
}
public?void?setName(String?name)?{
this.name?=?name;
}
public?String?getSinger()?{
return?singer;
}
public?void?setSinger(String?singer)?{
this.singer?=?singer;
}
}
public?class?MusicMain?{
static?void?add(Music?music,?ListMusic?musicList)?{
musicList.add(music);
}
static?void?save(ListMusic?musicList)?throws?IOException?{
StringBuilder?builder?=?new?StringBuilder();
for?(Music?music?:?musicList)?{
builder.append(music.getId()).append(",")
.append(music.getName()).append(",")
.append(music.getSinger()).append(System.lineSeparator());
}
File?file?=?new?File("mylist.txt");
FileWriter?writer?=?null;
try?{
writer?=?new?FileWriter(file);
writer.write(builder.toString());
}?finally?{
if?(writer?!=?null)?{
writer.close();
}
}
}
public?static?void?main(String[]?args)?{
ListMusic?musicList?=?new?ArrayList();
Music?music1?=?new?Music(1,?"成都.mp3",?"赵雷");
add(music1,?musicList);
Music?music2?=?new?Music(2,?"荷塘月色.mp3",?"凤凰传奇");
add(music2,?musicList);
Music?music3?=?new?Music(3,?"贵妃醉酒.mp3",?"李玉刚");
add(music3,?musicList);
try?{
save(musicList);
}?catch?(IOException?e)?{
System.out.println("保存失败。");
}
}
}
定义一个ArrayList集合对象
1、新建java类,TestArraylist.java;
2、编写代码,定义一个ArrayList集合对象,往其中添加随机产生的0-10之间的int类型的数据,并打印list内容;
ArrayListInteger list = new ArrayListInteger();
Random random = new Random();
for (int i = 0; i 10; i++) {
int num = random.nextInt(10);
list.add(num);
}
System.out.println(list);
3、编写代码,把其中的偶数逐个打印输出;
for (Integer integer : list) {
if (integer % 2 == 0) {
System.out.println(integer);
}
}
4、执行代码,查看执行结果,满足要求;
如何创建一个list类的泛型集合实例
泛型. 如果你不加这个的话 你的List就可以放进去所有类型的对象 取出来的时候都变成了Object对象 使用的时候需要进行强制类型转换 加了的话List只能存String 取出来也是String不需要强制类型转换