新闻类
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; /** * 新闻测试类 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 news:list) { System.out.print(news.getId()+","+news.getTitle()+news.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)); //删除索引对象,返回对象 } }