Android 如何在ArrayList中获取最大值
我想知道如何比较数组列表中的所有数组列表元素?我想比较最大数的元素。就像比较第一个元素和第二个元素一样,第二个元素和第三个元素进行比较。怎么做Android 如何在ArrayList中获取最大值,android,arraylist,compare,Android,Arraylist,Compare,我想知道如何比较数组列表中的所有数组列表元素?我想比较最大数的元素。就像比较第一个元素和第二个元素一样,第二个元素和第三个元素进行比较。怎么做 List <Product> productList= new ArrayList<>(); 谢谢你的帮助。比较一下这样的东西 for (int i = 0; i < productList.size(); i++) { for (int j = i+1; j < productList.size(); j++
List <Product> productList= new ArrayList<>();
谢谢你的帮助。比较一下这样的东西
for (int i = 0; i < productList.size(); i++) {
for (int j = i+1; j < productList.size(); j++) {
// compare productList.get(i) and productList.get(j)
}
}
比较一下这样的东西
for (int i = 0; i < productList.size(); i++) {
for (int j = i+1; j < productList.size(); j++) {
// compare productList.get(i) and productList.get(j)
}
}
如果您只想要最大值,请使用以下选项:
public int getMax(ArrayList list){
int max = Integer.MIN_VALUE;
for(int i=0; i<list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}
比较法是更好的方法:
public class compareProduct implements Comparator<Product> {
public int compare(Product a, Product b) {
if (a.getPrice() > b.getPrice())
return -1; // highest value first
if (a.getPrice() == b.getPrice())
return 0;
return 1;
}
}
然后就这样做:
产品p=Collections.maxproducts,新的compareProduct 如果您只想要最大值,请使用以下选项:
public int getMax(ArrayList list){
int max = Integer.MIN_VALUE;
for(int i=0; i<list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}
比较法是更好的方法:
public class compareProduct implements Comparator<Product> {
public int compare(Product a, Product b) {
if (a.getPrice() > b.getPrice())
return -1; // highest value first
if (a.getPrice() == b.getPrice())
return 0;
return 1;
}
}
然后就这样做:
产品p=Collections.maxproducts,新的compareProduct 你需要对列表进行排序吗?不需要,我想得到arraylistyeah中的最大数字,对数组进行排序,得到第一个或最后一个元素,然后使用for循环检查每个值,并存储最大值。你需要对列表进行排序吗?不需要,我想得到arraylistyeah中的最大数字,对数组进行排序,获取第一个或最后一个元素,然后使用for循环检查每个值,并存储最大值为什么使用内部循环?您可以比较productList.geti和maxwhy来使用内部循环?您可以比较productList.geti和maxShortest版本Integer.comparea.getPrice,b.getPrice最短版本Integer.comparea.getPrice,b.getPrice