李沃晟 2017-07-25 1131浏览量
数组序列
1.依次按照顺序向ArrayList中添加数据
用法:
将a添加到list中
list.add("a");
2.在第N个位置添加一个数据
用法:
在第1个位置添加E
list.add(1, "E");
注意:1.如果x位置上已经有元素则会取代原有元素的位置,原有元素会后移
2.ArrayList中必须有足够多的数据,例如ArrayList中没有任何数据,这个时候使用arraylist.add(1, "E");就会出现java.lang.IndexOutOfBoundsException异常。
Course cr1=new Course("1","数据结构");
coursesToSelect.add(cr1);//依次向List里添加数据
Course temp= (Course) coursesToSelect.get(0);//temp=第0个元素
Course cr2=new Course("2","C语言");
coursesToSelect.add(1,cr2);//在第1个位置添加cr2,如果第x个位置有元素就自动后移在x+1的位置添加,get与index值一致
/*
*利用迭代器输出List
*/
public void testIterator(){
Iterator it=coursesToSelect.iterator();
System.out.println("有以下课程待选(迭代器访问)");
while (it.hasNext()){
Course cr= (Course) it.next();
System.out.println("课程序号:"+cr.id+";课程名称:"+cr.name);
}
}
public void testModify(){
coursesToSelect.set(4,new Course("4","毛概"));
}
原理:系统会对list中的每个元素e调用o.equals(e),方法,加入list中有n个元素,那么会调用n次o.equals(e),只要有一次o.equals(e)返回了true,那么list.contains(o)返回true,否则返回false。
public void testListCoures(){
Course course= (Course) coursesToSelect.get(0);
System.out.println("取得备选课程"+course.name);
System.out.println("List是否存在备选课程"+coursesToSelect.contains(course));
}
contains方法调用equals()方法实现比较,如果需要比较List中是否存在某个值,则需要重写equals()方法
@Override
public boolean equals(Object obj) {
if (this == obj) //比较两个obj的值是否相等
return true;
if (obj == null) //如果obj值为空
return false;
if (!(obj instanceof Course)) //obj是否为Course的实例
return false;
Course other = (Course) obj; //创建实例other赋值obj
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
注:如果一个List中存在多个相同值,则IndexOf()返回第一个值的索引位置,
lastIndexOf()则返回最后一个值的索引位置。
Set中,添加某个对象,无论添加多少次, 最终只会保留一个该对象(的引用), 并且,保留的是第一次添加的那一个
for (Course cr : st.coursesToSelect) {
if (cr.id.equals(courseid)) {
student.courses.add(cr);
/**
* Set中,添加某个对象,无论添加多少次, 最终只会保留一个该对象(的引用), 并且,保留的是第一次添加的那一个
*/
student.courses.add(null);//set可以添加null值
student.courses.add(cr);
}
}
<key,value>
public void sort1(){
List<Integer> integerList=new ArrayList<Integer>();
Random random=new Random();
Integer t;
for (int i=0;i<10;i++){
do {
t=random.nextInt(100);//向List中添加10个100以内的整数
}while (integerList.contains(t));
integerList.add(t);
System.out.println("成功添加"+t);
}
System.out.println("———————————排序前———————————");
for (Integer integer:integerList
) {
System.out.println("元素"+integer);
}
System.out.println("———————————排序后———————————");
//******************************************
//调用Collections的sort方法对integerList进行排序
Collections.sort(integerList);
for (Integer integer:integerList
) {
System.out.println("元素"+integer);
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
集结各类场景实战经验,助你开发运维畅行无忧