import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class Demo01 {
public static void main(String[] args) {
/* LinkedList的使用
存储结构:双向链表
LinkedList源码分析:
int size; 集合的大小
Node first; 链表的头节点
Node last; 链表的尾节点
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item; 当前的数据
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
*/
//创建集合
LinkedList linkedList = new LinkedList<>();
//1.添加元素
Student s1 = new Student("张三", 16);
Student s2 = new Student("李四", 16);
Student s3 = new Student("王五", 16);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println("元素个数:"+linkedList.size());//元素个数:3
System.out.println(linkedList);//[Student{name='张三', age=16}, Student{name='李四', age=16}, Student{name='王五', age=16}]
//2.删除元素
linkedList.remove(s1);
System.out.println("元素个数:"+linkedList.size());//元素个数:2
System.out.println(linkedList);//Student{name='李四', age=16}, Student{name='王五', age=16}]
//3.遍历元素
//1.for遍历
for (int i = 0; i <linkedList.size() ; i++) {
System.out.println(linkedList.get(i));
}
//2.增强for遍历
for (Object o:
linkedList) {
Student s = (Student)o;
System.out.println(s);
}
//3.使用迭代器
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//4.使用ListIterator迭代器
ListIterator listIterator = linkedList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
//4.判断
System.out.println(linkedList.contains(s2));//true
System.out.println(linkedList.isEmpty());//false
//5.获取位置
System.out.println(linkedList.indexOf(s3));//0
}
}
public class Student {标签:name,LinkedList,age,System,Student,使用,println,linkedList From: https://www.cnblogs.com/123456dh/p/17133260.html
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object obj) {
//1.判断是否为空
if(obj==null){
return false;
}
//2.判断是否为同一个对象
if(obj==this){
return true;
}
//判断是否可转为Student类型
if(obj instanceof Student){
Student s=(Student) obj;//强转
if(this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
return false;
}
}