6、LinkList的使用
(1)使用链表结构实现、增删快但是查询慢
- 添加元素
//创建链表集合
LinkedList linkedList=new LinkedList ();
//添加元素
Student s1=new Student ("lym",10);
Student s2=new Student ("yummy",10);
Student s3=new Student ("happy",10);
linkedList.add (s1);
linkedList.add (s2);
linkedList.add (s3);
System.out.println (linkedList.size ());
System.out.println (linkedList.toString ());
- 删除测试
//删除元素
linkedList.remove (new Student ("lym",10));
System.out.println (linkedList.size ());
- 遍历测试
for循环
for(int i=0;i<linkedList.size ();i++){
System.out.println (linkedList.get (i));
}
增强for
//增强for
for(Object o:linkedList){
String s=(String) o;
System.out.println (s);
}
迭代器Iterator
//迭代器Iterator
Iterator iterator=linkedList.iterator ();
while (iterator.hasNext ()){
System.out.println (iterator.next ());
}
迭代器ListIterator
//迭代器ListIterator
ListIterator listIterator=linkedList.listIterator ();
while (listIterator.hasNext ()){
System.out.println (listIterator.next ());
}
(2)代码整合
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
/** * @author LYM * @date 2021/3/12 */
public class ch09_linklist {
public static void main(String[] args) {
//创建链表集合
LinkedList linkedList=new LinkedList ();
//添加元素
Student s1=new Student ("lym",10);
Student s2=new Student ("yummy",10);
Student s3=new Student ("happy",10);
linkedList.add (s1);
linkedList.add (s2);
linkedList.add (s3);
System.out.println (linkedList.size ());
System.out.println (linkedList.toString ());
//删除元素
// linkedList.remove (new Student ("lym",10));
// System.out.println (linkedList.size ());
for(int i=0;i<linkedList.size ();i++){
System.out.println (linkedList.get (i));
}
//增强for
for(Object o:linkedList){
String s=(String) o;
System.out.println (s);
}
//迭代器Iterator
Iterator iterator=linkedList.iterator ();
while (iterator.hasNext ()){
System.out.println (iterator.next ());
}
//迭代器ListIterator
ListIterator listIterator=linkedList.listIterator ();
while (listIterator.hasNext ()){
System.out.println (listIterator.next ());
}
}
}
其实这些操作代码和前面说的ArrayList很类似,所以这里就当作复习一遍,其实链表这个数据结果我个人觉得好难理解,特别是那些结点呀指针呀哈哈哈
今天的文章6、LinkList的使用分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/11551.html