编写博客目的:本系列博客均根据B站黑马程序员系列视频学习和编写目的在于记录自己的学习点滴,方便后续回忆和查找相关知识点,不足之处恳请各位有缘的朋友指正。文章来源地址https://www.toymoban.com/news/detail-824182.html
一、查找id对应的集合索引
package www.itheima;
import java.util.ArrayList;
public class ArrayListDemo7 {
public static void main(String[] args) {
ArrayList<User> list = new ArrayList<>();
User u1 = new User("001", "zhangsan", "123456");
User u2 = new User("002", "wangwu", "123456");
User u3 = new User("003", "lisi", "123456");
list.add(u1);
list.add(u2);
list.add(u3);
System.out.println(getIndex(list,"002"));
}
public static int getIndex(ArrayList<User> list, String id) {
for (int i = 0; i < list.size(); i++) {
User u = list.get(i);
String uid = u.getId();
if (uid.equals(id)) {
return i;
}
}
return -1;
}
}
二、返回手机价格低于三千的手机
package www.itheima;
import java.util.ArrayList;
public class ArrayListDemo8 {
public static void main(String[] args) {
ArrayList<Phone> list = new ArrayList<>();
Phone p1 = new Phone("小米", 1000);
Phone p2 = new Phone("苹果", 8000);
Phone p3 = new Phone("锤子", 2999);
list.add(p1);
list.add(p2);
list.add(p3);
ArrayList<Phone> phoneInfoList = getPhoneInfo(list);
for (int i = 0; i < phoneInfoList.size(); i++) {
Phone phone = phoneInfoList.get(i);
System.out.println(phone.getBrand() + "," + phone.getPrice());
}
}
// 定义一个方法,返回手机价格低于3000的手机
public static ArrayList<Phone> getPhoneInfo(ArrayList<Phone> list) {
ArrayList<Phone> resultList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Phone p = list.get(i);
int price = p.getPrice();
if (price < 3000) {
resultList.add(p);
}
}
return resultList;
}
}
文章来源:https://www.toymoban.com/news/detail-824182.html
到了这里,关于Java零基础学习20:集合的练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!