可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to know the way to find the second largest element among an array of objects. for eg. if there is an array of objects of a Book class with attributes like book name, price, in stock quantity
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);
How can we list the book with second largest price along with other attributes like name and in stock quantity
回答1:
Make a List
of Books
from it, sort it using Collections.sort
and take the element on index 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)); }
回答2:
Implements a Comparator
And sort your array, then pick second element.
class BookPriceComparator implements Comparator<Book> { @Override public int compare(Book a, Book b) { return a.getPrice() - b.getPrice(); } } Arrays.sort(bookArr, new BookPriceComparator ());
回答3:
You can loop through this Array to find the largest and with this the second largest Element of the Array. Because the Elements are Objects you have to get the Value that you want to compare from the element with a getter or the variable is public in the objects.
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; }
回答4:
- I think you should implements Interface
Comparable.
- and then use
Collections.sort();
回答5:
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 } }