首页 > 其他 > 详细

ArrayList用法

时间:2019-02-23 19:42:33      阅读:152      评论:0      收藏:0      [点我收藏+]

新闻类

 

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;
    }

}
    

 新闻测试类

package com.jihekuangjia;

import java.util.ArrayList;

/**
 * 新闻测试类
 * @author Administrator
 *
 */
public class NewsTest {
    public static void main(String[] args) {
        /*
         * 创建新闻类集合
         */
        ArrayList<News> list=new ArrayList<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.add(n3);
        list.add(n4);
        list.set(1, n1);    //在index索引位置的元素替换对象
        
        /*
         * 显示集合中的对象总数
         */
        System.out.println("新闻总数:"+list.size());
        
        /*
         * 在指定索引取出对象
         */
        News n=(News)list.get(1);        //取出的是object类型,进行强转
        System.out.println("get后取出的对象:"+n.getId()+","+n.getTitle()+","+n.getAuthor());
        
        /*
         * 指定对象取出下标
         */
        System.out.println("indexOf取对象n1:"+list.indexOf(n1));
        
        /*
         *遍历集合 
         */
        for(News obj:list) {
            System.out.print(obj.getId()+","+obj.getTitle()+obj.getAuthor());
            System.out.println();
        }
        
        /*
         * 判断列表中是否存在指定元素,返回boolean类型
         */
        System.out.println(list.contains(n1));
        System.out.println(list.contains(n2));
        
        /*
         * 删除对象
         */
        System.out.println("删除对象,返回boolean:"+list.remove(n1));        //删除对象,返回boolean
        System.out.println("删除索引对象,返回对象:"+list.remove(1));            //删除索引对象,返回对象
        
    }
}

 

 技术分享图片

 

ArrayList用法

原文:https://www.cnblogs.com/zzh630/p/10423884.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!