我需要知道在对象数组中找到第二大元素的方法。例如。 如果Book类的对象数组具有书名,价格,库存数量
等属性Book[] b=new Book[];
b[0]=new Book("x",200,50);
b[1]=new Book("y",100,44);
b[2]=new Book("z",500,29);
我们如何列出具有第二大价格的图书以及名称和库存数量等其他属性
答案 0 :(得分:3)
从List
创建Books
,使用Collections.sort
对其进行排序,并将索引为1。
List<Book> booklist = new ArrayList<Book>(Arrays.asList(b));
Collections.sort(booklist, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o2.getPrice() - o1.getPrice();
}
});
if (booklist.size() > 1) {
System.out.println(booklist.get(1));
}
答案 1 :(得分:2)
实现Comparator
并对数组进行排序,然后选择第二个元素。
class BookPriceComparator implements Comparator<Book> {
@Override
public int compare(Book a, Book b) {
return a.getPrice() - b.getPrice();
}
}
Arrays.sort(bookArr, new BookPriceComparator ());
答案 2 :(得分:1)
您可以遍历此数组以查找最大的数组,并使用此数组的第二大元素。因为元素是对象,所以你必须从元素中获取要与getter进行比较的Value,或者变量在对象中是公共的。
public int getSecondLargest(Object[] obj){
int length = obj.length;
int largest = 0;
int secondLargest = 0;
for(int i = 0; i<length; i++){
if(obj[largest].getValue() <= obj[i].getValue()){
secondLargest = largest;
largst = i;
}
}
return secondLargest;
}
答案 3 :(得分:1)
Comparable.
Collections.sort();
答案 4 :(得分:1)
import java.util.*;
//here you can make changes or you can create your own new class
//to sort book according to pages
class sortPrice implements Comparator<Test> {
public int compare(Test i1, Test i2) {
Integer x = i1.getPrice(), y = i2.getPrice();
return y.compareTo(x); // <--- changed
}
}
// in your case Test class could be Book class
public class Test {
/**
* @param args
*/
int price , page ;
String name;
Test(String n , int p ,int pg){
name=n;
price=p;
page=pg;
}
public String toString(){
return name+" "+price +" "+page ;
}
public String getName(){
return name;
}
public int getPage(){
return page;
}
public int getPrice(){
return price;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test[] b=new Test[3];
b[0]=new Test("x",200,50);
b[1]=new Test("y",100,44);
b[2]=new Test("z",500,29);
ArrayList<Test> a = new ArrayList<>();
for(int i=0;i<3;i++){
a.add(b[i]);
}
sortPrice s= new sortPrice(); // required to pass as argument to tell
//based on which sorting order you want to sort
Collections.sort(a,s ); //here we are sorting Test(Book) based on price.
System.out.println(a.get(1)); // printing arrayList //<----- changed
}
}