Java教程

编程题-集合相关

本文主要是介绍编程题-集合相关,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

按要求实现:

(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 +
                '}';
    }
}

 

这篇关于编程题-集合相关的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!