编程题-集合相关

按要求实现:

(1) 封装个新闻类,包含标题和内容属性,提供get、set方法,重写toString方法, 打印对象空时只打印标题;
 (2)只提供一个带参数的构造器,实例化对象时,只初始化标题;并且实例化两个对象:

  新闻一:新冠确诊病例超干万,数百万印度教信徒赴恒河“圣浴”引民众担忧
  新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生

(3)将新闻对象添加到ArrayList集合中,并且进行倒序遍历;

(4)在遍历集合过程中,对新闻标题进行处理,超过15字的只保留前15个,然后在后边加“...”

(5)在控制台打印遍历出经过处理的新闻标题;

package com.lin.test_;

import java.util.ArrayList;

public class text1 {

    public static void main(String[] args) {

        News news1 = new News(new StringBuilder("新冠确诊病例超千万,数百万印度信徒赴恒河“圣浴”引民众担忧"));
        News news2 = new News(new StringBuilder("男子突然想起2个月前钓的鱼还在网兜里。捞起一看赶紧放生"));

        ArrayList arrayList = new ArrayList();
        arrayList.add(news1);
        arrayList.add(news2);

        News news;
        int length;
        StringBuilder stringBuilder;

        for (int i = arrayList.size() - 1; i >= 0; i--) {
            news = (News) arrayList.get(i);
            length = news.getTitle().length();

            if (length > 15) {
                stringBuilder = new StringBuilder(news.getTitle());
                System.out.println(stringBuilder.replace(15, length, "..."));
                break;
            }

            System.out.println(news.getTitle());
            //未修改原数据
            System.out.println(arrayList.get(i));
        }

    }




}

class News {
    private StringBuilder title;
    private StringBuilder content;

    public News(StringBuilder title) {
        this.title = title;
    }

    public StringBuilder getTitle() {
        return title;
    }

    public void setTitle(StringBuilder title) {
        this.title = title;
    }

    public StringBuilder getContent() {
        return content;
    }

    public void setContent(StringBuilder content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title=" + title +
                '}';
    }
}

 

上一篇:数据分析修炼历程:你在哪一站?


下一篇:31HUI - 滚动公告组件(hui-scroll-news)