题1:
1.封装一个新闻类:包含标题和内容属性,提供get,set方法,重写toString方法,打印对象时只打印标题
2.只提供一个带参数的构造器,实例化对象。只初始化标题。并实例化对象:
新闻一:新冠确诊病例超千万,数百万印度教信徒赴恒河“圣浴” 引民众担忧
新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生
新闻三:我在南京梧桐道行走
3.将新闻对象添加到ArrayList集合中,并且进行倒叙遍历
4.在遍历过程中,对新闻标题进行处理,超过15字的只保留15个,然后再后边加“+”
5.在控制台打印遍历出经过处理的新闻标题
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new News("新冠确诊病例超千万,数百万印度教信徒赴恒河“圣浴” 引民众担忧"));
arrayList.add(new News("男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生"));
arrayList.add(new News("我在南京梧桐道行走"));
int size = arrayList.size();//获取arrayList的字符串的长度
for (int i = size-1; i >= 0 ; i--) {//递减排序
News news = (News)arrayList.get(i);//进行强转为 News 类型
System.out.println(processtitle(news.getTitle()));
}
}
//提供方法进行判断
public static String processtitle (String title){
if(title == null) {
return " ";//若字符串为空,则返回空
}else if(title.length() > 15){//判断大于 15的字符串长度
return title.substring(0,15) + "...";//将大于 15 的字符串长度 截取15的长度并在后面添加...
}else
return title;//都不满足则原路返回
}
//新闻类
class News{
private String title;
private String content;
public News(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "title='" + title;
}
}
题2:
使用ArrayList完成对象,Car{name,price}的各种操作
1.add:添加单个元素
2.remove:删除指定元素
3.contains:查找元素是否存在
4.size:获取元素个数
5.isEmpty: 判断是否为空
6.clear:清空
7.addAll:添加多个元素
8.containsAll:查找多个元素是否都存在
9.removeAll:删除多个元素
使用增强for和迭代器来遍历所有的car,需要重写Car的toString方法
题3:
要求:
1.使用HashMap类实例化一个Map类型的对象m,键(String)和值(int)分别用于存储员工的姓名和工资,存入数据为:jack-650;tom-1200;smith-2900
2.将jack的工资改为2600
3.为所有员工工资都加100
4.遍历集合中所有的员工
5.遍历集合中所有的工资
public static void main(String[] args) {
Map map = new HashMap();
map.put("jack",650);
map.put("tom",1200);
map.put("smith",2900);
//1.将jack的工资改为2600元
map.remove("jack",2600);
//2.对所有员工进行 + 100
Set set = map.keySet();
for (Object key :set) {
//为所有的员工工资加薪100元
Integer price = (Integer) map.get(key) + 100;
map.put(key,price);
}
System.out.println(map);
System.out.println("===========增强for遍历==============");
Set set1 = map.keySet();
for (Object key :set1) {
System.out.println(key + "=" + map.get(key));;
}
System.out.println("===========迭代器遍历==============");
Iterator iterator = set1.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next + "=" + map.get(next));
}
}
题4:
分析HashSet和TreeSet分别如何实现去重的
1)HashSet的去重机制;hashCode() + equals() ,底层先通过存入对象,进行运算得到一个hash值,通过hash值得到对应的索引,如果发现table索引所在的位置,没有数据,就直接存放;如果有数据,就进行equlas比较{遍历比较},如果比较后,不相同,就加入。否则就不加入。
2)TreeSet的去重机制;如果你传入一个Comparator匿名对象,就使用实现的compara去重,如果方法返回0,就认为是相同的元素或者数据,就不添加,如果你没有传入一个Comparator匿名对象,则以你添加的对象实现的Comparaable接口的comparaTo去重
5081

被折叠的 条评论
为什么被折叠?



