LinkedList用法

新闻类

 

package com.jihekuangjia;
/**
 * 新闻类
 * @author Administrator
 *
 */
public class News {
    private int id;                //Id
    private String title;        //标题
    private String author;        //内容
    
    /**
     * 构造方法
     */
    public News() {}
    public News(int id, String title, String author) {
        super();
        this.id = id;
        this.title = title;
        this.author = author;
    }

    /**
     * setter getter
     */
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

}
    

 

新闻测试类LinkedList

 

package com.jihekuangjia;

import java.util.LinkedList;

/**
 * 新闻测试类 LinkedList
 * @author Administrator
 *
 */
public class NewsTest2 {
    public static void main(String[] args) {
        //创建链表新闻集合
        LinkedList<News> list=new LinkedList<News>();

        //创建对象
        News n1=new News(1,"春天到了","小鱼");
        News n2=new News(2,"夏天到了","小鸡");
        News n3=new News(3,"秋天到了","小狗");
        News n4=new News(4,"冬天到了","小猫");    
        
        //添加对象
        list.add(n1);        //对象放入集合
        list.add(1,n2);        //在指定下标放入集合
        list.addFirst(n3);    //在首添加对象
        list.addLast(n4);    //在尾添加对象
        list.set(1, n1);    //在index索引位置的元素替换对象
        
        //输入新闻集合
        for(News news:list) {
            System.out.print(news.getId()+","+news.getTitle()+news.getAuthor());
            System.out.println();
        }
        
        //get取出对象
        System.out.println("指定下标取出对象:"+list.get(1));
        System.out.println("取出第一个对象:"+list.getFirst());
        System.out.println("取出末尾的对象:"+list.getLast());
        
        //remove删除对象
        System.out.println("删除对象返回boolean:"+list.remove(n1));
        System.out.println("删除第一个对象:"+list.removeFirst());
        System.out.println("删除最后的对象:"+list.removeLast());
    }
}

 

 

运行

 

posted @ 2019-02-23 19:59  纸灰  阅读(732)  评论(0编辑  收藏  举报